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 // This file defines the Type interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_TYPE_H
15 #define LLVM_CLANG_AST_TYPE_H
17 #include "clang/AST/NestedNameSpecifier.h"
18 #include "clang/AST/TemplateName.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/ExceptionSpecificationType.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/Linkage.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "clang/Basic/Visibility.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/FoldingSet.h"
28 #include "llvm/ADT/iterator_range.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/ADT/PointerUnion.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/ErrorHandling.h"
37 TypeAlignmentInBits = 4,
38 TypeAlignment = 1 << TypeAlignmentInBits
47 class PointerLikeTypeTraits;
49 class PointerLikeTypeTraits< ::clang::Type*> {
51 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
52 static inline ::clang::Type *getFromVoidPointer(void *P) {
53 return static_cast< ::clang::Type*>(P);
55 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
58 class PointerLikeTypeTraits< ::clang::ExtQuals*> {
60 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
61 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
62 return static_cast< ::clang::ExtQuals*>(P);
64 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
68 struct isPodLike<clang::QualType> { static const bool value = true; };
73 class TypedefNameDecl;
75 class TemplateTypeParmDecl;
76 class NonTypeTemplateParmDecl;
77 class TemplateTemplateParmDecl;
84 class ObjCInterfaceDecl;
85 class ObjCProtocolDecl;
87 class UnresolvedUsingTypenameDecl;
91 class StmtIteratorBase;
92 class TemplateArgument;
93 class TemplateArgumentLoc;
94 class TemplateArgumentListInfo;
97 class ExtQualsTypeCommonBase;
98 struct PrintingPolicy;
100 template <typename> class CanQual;
101 typedef CanQual<Type> CanQualType;
103 // Provide forward declarations for all of the *Type classes
104 #define TYPE(Class, Base) class Class##Type;
105 #include "clang/AST/TypeNodes.def"
107 /// Qualifiers - The collection of all-type qualifiers we support.
108 /// Clang supports five independent qualifiers:
109 /// * C99: const, volatile, and restrict
110 /// * Embedded C (TR18037): address spaces
111 /// * Objective C: the GC attributes (none, weak, or strong)
114 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
118 CVRMask = Const | Volatile | Restrict
128 /// There is no lifetime qualification on this type.
131 /// This object can be modified without requiring retains or
135 /// Assigning into this object requires the old value to be
136 /// released and the new value to be retained. The timing of the
137 /// release of the old value is inexact: it may be moved to
138 /// immediately after the last known point where the value is
142 /// Reading or writing from this object requires a barrier call.
145 /// Assigning into this object requires a lifetime extension.
150 /// The maximum supported address space number.
151 /// 24 bits should be enough for anyone.
152 MaxAddressSpace = 0xffffffu,
154 /// The width of the "fast" qualifier mask.
157 /// The fast qualifier mask.
158 FastMask = (1 << FastWidth) - 1
161 Qualifiers() : Mask(0) {}
163 /// \brief Returns the common set of qualifiers while removing them from
165 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
166 // If both are only CVR-qualified, bit operations are sufficient.
167 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
169 Q.Mask = L.Mask & R.Mask;
176 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
177 Q.addCVRQualifiers(CommonCRV);
178 L.removeCVRQualifiers(CommonCRV);
179 R.removeCVRQualifiers(CommonCRV);
181 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
182 Q.setObjCGCAttr(L.getObjCGCAttr());
183 L.removeObjCGCAttr();
184 R.removeObjCGCAttr();
187 if (L.getObjCLifetime() == R.getObjCLifetime()) {
188 Q.setObjCLifetime(L.getObjCLifetime());
189 L.removeObjCLifetime();
190 R.removeObjCLifetime();
193 if (L.getAddressSpace() == R.getAddressSpace()) {
194 Q.setAddressSpace(L.getAddressSpace());
195 L.removeAddressSpace();
196 R.removeAddressSpace();
201 static Qualifiers fromFastMask(unsigned Mask) {
203 Qs.addFastQualifiers(Mask);
207 static Qualifiers fromCVRMask(unsigned CVR) {
209 Qs.addCVRQualifiers(CVR);
213 // Deserialize qualifiers from an opaque representation.
214 static Qualifiers fromOpaqueValue(unsigned opaque) {
220 // Serialize these qualifiers into an opaque representation.
221 unsigned getAsOpaqueValue() const {
225 bool hasConst() const { return Mask & Const; }
226 void setConst(bool flag) {
227 Mask = (Mask & ~Const) | (flag ? Const : 0);
229 void removeConst() { Mask &= ~Const; }
230 void addConst() { Mask |= Const; }
232 bool hasVolatile() const { return Mask & Volatile; }
233 void setVolatile(bool flag) {
234 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
236 void removeVolatile() { Mask &= ~Volatile; }
237 void addVolatile() { Mask |= Volatile; }
239 bool hasRestrict() const { return Mask & Restrict; }
240 void setRestrict(bool flag) {
241 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
243 void removeRestrict() { Mask &= ~Restrict; }
244 void addRestrict() { Mask |= Restrict; }
246 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
247 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
248 void setCVRQualifiers(unsigned mask) {
249 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
250 Mask = (Mask & ~CVRMask) | mask;
252 void removeCVRQualifiers(unsigned mask) {
253 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
256 void removeCVRQualifiers() {
257 removeCVRQualifiers(CVRMask);
259 void addCVRQualifiers(unsigned mask) {
260 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
264 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
265 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
266 void setObjCGCAttr(GC type) {
267 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
269 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
270 void addObjCGCAttr(GC type) {
274 Qualifiers withoutObjCGCAttr() const {
275 Qualifiers qs = *this;
276 qs.removeObjCGCAttr();
279 Qualifiers withoutObjCLifetime() const {
280 Qualifiers qs = *this;
281 qs.removeObjCLifetime();
285 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
286 ObjCLifetime getObjCLifetime() const {
287 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
289 void setObjCLifetime(ObjCLifetime type) {
290 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
292 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
293 void addObjCLifetime(ObjCLifetime type) {
295 assert(!hasObjCLifetime());
296 Mask |= (type << LifetimeShift);
299 /// True if the lifetime is neither None or ExplicitNone.
300 bool hasNonTrivialObjCLifetime() const {
301 ObjCLifetime lifetime = getObjCLifetime();
302 return (lifetime > OCL_ExplicitNone);
305 /// True if the lifetime is either strong or weak.
306 bool hasStrongOrWeakObjCLifetime() const {
307 ObjCLifetime lifetime = getObjCLifetime();
308 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
311 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
312 unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
313 void setAddressSpace(unsigned space) {
314 assert(space <= MaxAddressSpace);
315 Mask = (Mask & ~AddressSpaceMask)
316 | (((uint32_t) space) << AddressSpaceShift);
318 void removeAddressSpace() { setAddressSpace(0); }
319 void addAddressSpace(unsigned space) {
321 setAddressSpace(space);
324 // Fast qualifiers are those that can be allocated directly
325 // on a QualType object.
326 bool hasFastQualifiers() const { return getFastQualifiers(); }
327 unsigned getFastQualifiers() const { return Mask & FastMask; }
328 void setFastQualifiers(unsigned mask) {
329 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
330 Mask = (Mask & ~FastMask) | mask;
332 void removeFastQualifiers(unsigned mask) {
333 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
336 void removeFastQualifiers() {
337 removeFastQualifiers(FastMask);
339 void addFastQualifiers(unsigned mask) {
340 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
344 /// hasNonFastQualifiers - Return true if the set contains any
345 /// qualifiers which require an ExtQuals node to be allocated.
346 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
347 Qualifiers getNonFastQualifiers() const {
348 Qualifiers Quals = *this;
349 Quals.setFastQualifiers(0);
353 /// hasQualifiers - Return true if the set contains any qualifiers.
354 bool hasQualifiers() const { return Mask; }
355 bool empty() const { return !Mask; }
357 /// \brief Add the qualifiers from the given set to this set.
358 void addQualifiers(Qualifiers Q) {
359 // If the other set doesn't have any non-boolean qualifiers, just
361 if (!(Q.Mask & ~CVRMask))
364 Mask |= (Q.Mask & CVRMask);
365 if (Q.hasAddressSpace())
366 addAddressSpace(Q.getAddressSpace());
367 if (Q.hasObjCGCAttr())
368 addObjCGCAttr(Q.getObjCGCAttr());
369 if (Q.hasObjCLifetime())
370 addObjCLifetime(Q.getObjCLifetime());
374 /// \brief Remove the qualifiers from the given set from this set.
375 void removeQualifiers(Qualifiers Q) {
376 // If the other set doesn't have any non-boolean qualifiers, just
377 // bit-and the inverse in.
378 if (!(Q.Mask & ~CVRMask))
381 Mask &= ~(Q.Mask & CVRMask);
382 if (getObjCGCAttr() == Q.getObjCGCAttr())
384 if (getObjCLifetime() == Q.getObjCLifetime())
385 removeObjCLifetime();
386 if (getAddressSpace() == Q.getAddressSpace())
387 removeAddressSpace();
391 /// \brief Add the qualifiers from the given set to this set, given that
392 /// they don't conflict.
393 void addConsistentQualifiers(Qualifiers qs) {
394 assert(getAddressSpace() == qs.getAddressSpace() ||
395 !hasAddressSpace() || !qs.hasAddressSpace());
396 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
397 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
398 assert(getObjCLifetime() == qs.getObjCLifetime() ||
399 !hasObjCLifetime() || !qs.hasObjCLifetime());
403 /// \brief Determines if these qualifiers compatibly include another set.
404 /// Generally this answers the question of whether an object with the other
405 /// qualifiers can be safely used as an object with these qualifiers.
406 bool compatiblyIncludes(Qualifiers other) const {
408 // Address spaces must match exactly.
409 getAddressSpace() == other.getAddressSpace() &&
410 // ObjC GC qualifiers can match, be added, or be removed, but can't be
412 (getObjCGCAttr() == other.getObjCGCAttr() ||
413 !hasObjCGCAttr() || !other.hasObjCGCAttr()) &&
414 // ObjC lifetime qualifiers must match exactly.
415 getObjCLifetime() == other.getObjCLifetime() &&
416 // CVR qualifiers may subset.
417 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
420 /// \brief Determines if these qualifiers compatibly include another set of
421 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
423 /// One set of Objective-C lifetime qualifiers compatibly includes the other
424 /// if the lifetime qualifiers match, or if both are non-__weak and the
425 /// including set also contains the 'const' qualifier.
426 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
427 if (getObjCLifetime() == other.getObjCLifetime())
430 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
436 /// \brief Determine whether this set of qualifiers is a strict superset of
437 /// another set of qualifiers, not considering qualifier compatibility.
438 bool isStrictSupersetOf(Qualifiers Other) const;
440 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
441 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
443 LLVM_EXPLICIT operator bool() const { return hasQualifiers(); }
445 Qualifiers &operator+=(Qualifiers R) {
450 // Union two qualifier sets. If an enumerated qualifier appears
451 // in both sets, use the one from the right.
452 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
457 Qualifiers &operator-=(Qualifiers R) {
462 /// \brief Compute the difference between two qualifier sets.
463 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
468 std::string getAsString() const;
469 std::string getAsString(const PrintingPolicy &Policy) const;
471 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
472 void print(raw_ostream &OS, const PrintingPolicy &Policy,
473 bool appendSpaceIfNonEmpty = false) const;
475 void Profile(llvm::FoldingSetNodeID &ID) const {
481 // bits: |0 1 2|3 .. 4|5 .. 7|8 ... 31|
482 // |C R V|GCAttr|Lifetime|AddressSpace|
485 static const uint32_t GCAttrMask = 0x18;
486 static const uint32_t GCAttrShift = 3;
487 static const uint32_t LifetimeMask = 0xE0;
488 static const uint32_t LifetimeShift = 5;
489 static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
490 static const uint32_t AddressSpaceShift = 8;
493 /// A std::pair-like structure for storing a qualified type split
494 /// into its local qualifiers and its locally-unqualified type.
495 struct SplitQualType {
496 /// The locally-unqualified type.
499 /// The local qualifiers.
502 SplitQualType() : Ty(nullptr), Quals() {}
503 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
505 SplitQualType getSingleStepDesugaredType() const; // end of this file
507 // Make std::tie work.
508 std::pair<const Type *,Qualifiers> asPair() const {
509 return std::pair<const Type *, Qualifiers>(Ty, Quals);
512 friend bool operator==(SplitQualType a, SplitQualType b) {
513 return a.Ty == b.Ty && a.Quals == b.Quals;
515 friend bool operator!=(SplitQualType a, SplitQualType b) {
516 return a.Ty != b.Ty || a.Quals != b.Quals;
520 /// QualType - For efficiency, we don't store CV-qualified types as nodes on
521 /// their own: instead each reference to a type stores the qualifiers. This
522 /// greatly reduces the number of nodes we need to allocate for types (for
523 /// example we only need one for 'int', 'const int', 'volatile int',
524 /// 'const volatile int', etc).
526 /// As an added efficiency bonus, instead of making this a pair, we
527 /// just store the two bits we care about in the low bits of the
528 /// pointer. To handle the packing/unpacking, we make QualType be a
529 /// simple wrapper class that acts like a smart pointer. A third bit
530 /// indicates whether there are extended qualifiers present, in which
531 /// case the pointer points to a special structure.
533 // Thankfully, these are efficiently composable.
534 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
535 Qualifiers::FastWidth> Value;
537 const ExtQuals *getExtQualsUnsafe() const {
538 return Value.getPointer().get<const ExtQuals*>();
541 const Type *getTypePtrUnsafe() const {
542 return Value.getPointer().get<const Type*>();
545 const ExtQualsTypeCommonBase *getCommonPtr() const {
546 assert(!isNull() && "Cannot retrieve a NULL type pointer");
547 uintptr_t CommonPtrVal
548 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
549 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
550 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
553 friend class QualifierCollector;
557 QualType(const Type *Ptr, unsigned Quals)
558 : Value(Ptr, Quals) {}
559 QualType(const ExtQuals *Ptr, unsigned Quals)
560 : Value(Ptr, Quals) {}
562 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
563 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
565 /// Retrieves a pointer to the underlying (unqualified) type.
567 /// This function requires that the type not be NULL. If the type might be
568 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
569 const Type *getTypePtr() const;
571 const Type *getTypePtrOrNull() const;
573 /// Retrieves a pointer to the name of the base type.
574 const IdentifierInfo *getBaseTypeIdentifier() const;
576 /// Divides a QualType into its unqualified type and a set of local
578 SplitQualType split() const;
580 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
581 static QualType getFromOpaquePtr(const void *Ptr) {
583 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
587 const Type &operator*() const {
588 return *getTypePtr();
591 const Type *operator->() const {
595 bool isCanonical() const;
596 bool isCanonicalAsParam() const;
598 /// isNull - Return true if this QualType doesn't point to a type yet.
599 bool isNull() const {
600 return Value.getPointer().isNull();
603 /// \brief Determine whether this particular QualType instance has the
604 /// "const" qualifier set, without looking through typedefs that may have
605 /// added "const" at a different level.
606 bool isLocalConstQualified() const {
607 return (getLocalFastQualifiers() & Qualifiers::Const);
610 /// \brief Determine whether this type is const-qualified.
611 bool isConstQualified() const;
613 /// \brief Determine whether this particular QualType instance has the
614 /// "restrict" qualifier set, without looking through typedefs that may have
615 /// added "restrict" at a different level.
616 bool isLocalRestrictQualified() const {
617 return (getLocalFastQualifiers() & Qualifiers::Restrict);
620 /// \brief Determine whether this type is restrict-qualified.
621 bool isRestrictQualified() const;
623 /// \brief Determine whether this particular QualType instance has the
624 /// "volatile" qualifier set, without looking through typedefs that may have
625 /// added "volatile" at a different level.
626 bool isLocalVolatileQualified() const {
627 return (getLocalFastQualifiers() & Qualifiers::Volatile);
630 /// \brief Determine whether this type is volatile-qualified.
631 bool isVolatileQualified() const;
633 /// \brief Determine whether this particular QualType instance has any
634 /// qualifiers, without looking through any typedefs that might add
635 /// qualifiers at a different level.
636 bool hasLocalQualifiers() const {
637 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
640 /// \brief Determine whether this type has any qualifiers.
641 bool hasQualifiers() const;
643 /// \brief Determine whether this particular QualType instance has any
644 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
646 bool hasLocalNonFastQualifiers() const {
647 return Value.getPointer().is<const ExtQuals*>();
650 /// \brief Retrieve the set of qualifiers local to this particular QualType
651 /// instance, not including any qualifiers acquired through typedefs or
653 Qualifiers getLocalQualifiers() const;
655 /// \brief Retrieve the set of qualifiers applied to this type.
656 Qualifiers getQualifiers() const;
658 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
659 /// local to this particular QualType instance, not including any qualifiers
660 /// acquired through typedefs or other sugar.
661 unsigned getLocalCVRQualifiers() const {
662 return getLocalFastQualifiers();
665 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
666 /// applied to this type.
667 unsigned getCVRQualifiers() const;
669 bool isConstant(ASTContext& Ctx) const {
670 return QualType::isConstant(*this, Ctx);
673 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
674 bool isPODType(ASTContext &Context) const;
676 /// isCXX98PODType() - Return true if this is a POD type according to the
677 /// rules of the C++98 standard, regardless of the current compilation's
679 bool isCXX98PODType(ASTContext &Context) const;
681 /// isCXX11PODType() - Return true if this is a POD type according to the
682 /// more relaxed rules of the C++11 standard, regardless of the current
683 /// compilation's language.
684 /// (C++0x [basic.types]p9)
685 bool isCXX11PODType(ASTContext &Context) const;
687 /// isTrivialType - Return true if this is a trivial type
688 /// (C++0x [basic.types]p9)
689 bool isTrivialType(ASTContext &Context) const;
691 /// isTriviallyCopyableType - Return true if this is a trivially
692 /// copyable type (C++0x [basic.types]p9)
693 bool isTriviallyCopyableType(ASTContext &Context) const;
695 // Don't promise in the API that anything besides 'const' can be
698 /// addConst - add the specified type qualifier to this QualType.
700 addFastQualifiers(Qualifiers::Const);
702 QualType withConst() const {
703 return withFastQualifiers(Qualifiers::Const);
706 /// addVolatile - add the specified type qualifier to this QualType.
708 addFastQualifiers(Qualifiers::Volatile);
710 QualType withVolatile() const {
711 return withFastQualifiers(Qualifiers::Volatile);
714 /// Add the restrict qualifier to this QualType.
716 addFastQualifiers(Qualifiers::Restrict);
718 QualType withRestrict() const {
719 return withFastQualifiers(Qualifiers::Restrict);
722 QualType withCVRQualifiers(unsigned CVR) const {
723 return withFastQualifiers(CVR);
726 void addFastQualifiers(unsigned TQs) {
727 assert(!(TQs & ~Qualifiers::FastMask)
728 && "non-fast qualifier bits set in mask!");
729 Value.setInt(Value.getInt() | TQs);
732 void removeLocalConst();
733 void removeLocalVolatile();
734 void removeLocalRestrict();
735 void removeLocalCVRQualifiers(unsigned Mask);
737 void removeLocalFastQualifiers() { Value.setInt(0); }
738 void removeLocalFastQualifiers(unsigned Mask) {
739 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
740 Value.setInt(Value.getInt() & ~Mask);
743 // Creates a type with the given qualifiers in addition to any
744 // qualifiers already on this type.
745 QualType withFastQualifiers(unsigned TQs) const {
747 T.addFastQualifiers(TQs);
751 // Creates a type with exactly the given fast qualifiers, removing
752 // any existing fast qualifiers.
753 QualType withExactLocalFastQualifiers(unsigned TQs) const {
754 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
757 // Removes fast qualifiers, but leaves any extended qualifiers in place.
758 QualType withoutLocalFastQualifiers() const {
760 T.removeLocalFastQualifiers();
764 QualType getCanonicalType() const;
766 /// \brief Return this type with all of the instance-specific qualifiers
767 /// removed, but without removing any qualifiers that may have been applied
768 /// through typedefs.
769 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
771 /// \brief Retrieve the unqualified variant of the given type,
772 /// removing as little sugar as possible.
774 /// This routine looks through various kinds of sugar to find the
775 /// least-desugared type that is unqualified. For example, given:
778 /// typedef int Integer;
779 /// typedef const Integer CInteger;
780 /// typedef CInteger DifferenceType;
783 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
784 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
786 /// The resulting type might still be qualified if it's sugar for an array
787 /// type. To strip qualifiers even from within a sugared array type, use
788 /// ASTContext::getUnqualifiedArrayType.
789 inline QualType getUnqualifiedType() const;
791 /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
792 /// given type, removing as little sugar as possible.
794 /// Like getUnqualifiedType(), but also returns the set of
795 /// qualifiers that were built up.
797 /// The resulting type might still be qualified if it's sugar for an array
798 /// type. To strip qualifiers even from within a sugared array type, use
799 /// ASTContext::getUnqualifiedArrayType.
800 inline SplitQualType getSplitUnqualifiedType() const;
802 /// \brief Determine whether this type is more qualified than the other
803 /// given type, requiring exact equality for non-CVR qualifiers.
804 bool isMoreQualifiedThan(QualType Other) const;
806 /// \brief Determine whether this type is at least as qualified as the other
807 /// given type, requiring exact equality for non-CVR qualifiers.
808 bool isAtLeastAsQualifiedAs(QualType Other) const;
810 QualType getNonReferenceType() const;
812 /// \brief Determine the type of a (typically non-lvalue) expression with the
813 /// specified result type.
815 /// This routine should be used for expressions for which the return type is
816 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
817 /// an lvalue. It removes a top-level reference (since there are no
818 /// expressions of reference type) and deletes top-level cvr-qualifiers
819 /// from non-class types (in C++) or all types (in C).
820 QualType getNonLValueExprType(const ASTContext &Context) const;
822 /// getDesugaredType - Return the specified type with any "sugar" removed from
823 /// the type. This takes off typedefs, typeof's etc. If the outer level of
824 /// the type is already concrete, it returns it unmodified. This is similar
825 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
826 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
829 /// Qualifiers are left in place.
830 QualType getDesugaredType(const ASTContext &Context) const {
831 return getDesugaredType(*this, Context);
834 SplitQualType getSplitDesugaredType() const {
835 return getSplitDesugaredType(*this);
838 /// \brief Return the specified type with one level of "sugar" removed from
841 /// This routine takes off the first typedef, typeof, etc. If the outer level
842 /// of the type is already concrete, it returns it unmodified.
843 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
844 return getSingleStepDesugaredTypeImpl(*this, Context);
847 /// IgnoreParens - Returns the specified type after dropping any
848 /// outer-level parentheses.
849 QualType IgnoreParens() const {
850 if (isa<ParenType>(*this))
851 return QualType::IgnoreParens(*this);
855 /// operator==/!= - Indicate whether the specified types and qualifiers are
857 friend bool operator==(const QualType &LHS, const QualType &RHS) {
858 return LHS.Value == RHS.Value;
860 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
861 return LHS.Value != RHS.Value;
863 std::string getAsString() const {
864 return getAsString(split());
866 static std::string getAsString(SplitQualType split) {
867 return getAsString(split.Ty, split.Quals);
869 static std::string getAsString(const Type *ty, Qualifiers qs);
871 std::string getAsString(const PrintingPolicy &Policy) const;
873 void print(raw_ostream &OS, const PrintingPolicy &Policy,
874 const Twine &PlaceHolder = Twine()) const {
875 print(split(), OS, Policy, PlaceHolder);
877 static void print(SplitQualType split, raw_ostream &OS,
878 const PrintingPolicy &policy, const Twine &PlaceHolder) {
879 return print(split.Ty, split.Quals, OS, policy, PlaceHolder);
881 static void print(const Type *ty, Qualifiers qs,
882 raw_ostream &OS, const PrintingPolicy &policy,
883 const Twine &PlaceHolder);
885 void getAsStringInternal(std::string &Str,
886 const PrintingPolicy &Policy) const {
887 return getAsStringInternal(split(), Str, Policy);
889 static void getAsStringInternal(SplitQualType split, std::string &out,
890 const PrintingPolicy &policy) {
891 return getAsStringInternal(split.Ty, split.Quals, out, policy);
893 static void getAsStringInternal(const Type *ty, Qualifiers qs,
895 const PrintingPolicy &policy);
897 class StreamedQualTypeHelper {
899 const PrintingPolicy &Policy;
900 const Twine &PlaceHolder;
902 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
903 const Twine &PlaceHolder)
904 : T(T), Policy(Policy), PlaceHolder(PlaceHolder) { }
906 friend raw_ostream &operator<<(raw_ostream &OS,
907 const StreamedQualTypeHelper &SQT) {
908 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder);
913 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
914 const Twine &PlaceHolder = Twine()) const {
915 return StreamedQualTypeHelper(*this, Policy, PlaceHolder);
918 void dump(const char *s) const;
921 void Profile(llvm::FoldingSetNodeID &ID) const {
922 ID.AddPointer(getAsOpaquePtr());
925 /// getAddressSpace - Return the address space of this type.
926 inline unsigned getAddressSpace() const;
928 /// getObjCGCAttr - Returns gc attribute of this type.
929 inline Qualifiers::GC getObjCGCAttr() const;
931 /// isObjCGCWeak true when Type is objc's weak.
932 bool isObjCGCWeak() const {
933 return getObjCGCAttr() == Qualifiers::Weak;
936 /// isObjCGCStrong true when Type is objc's strong.
937 bool isObjCGCStrong() const {
938 return getObjCGCAttr() == Qualifiers::Strong;
941 /// getObjCLifetime - Returns lifetime attribute of this type.
942 Qualifiers::ObjCLifetime getObjCLifetime() const {
943 return getQualifiers().getObjCLifetime();
946 bool hasNonTrivialObjCLifetime() const {
947 return getQualifiers().hasNonTrivialObjCLifetime();
950 bool hasStrongOrWeakObjCLifetime() const {
951 return getQualifiers().hasStrongOrWeakObjCLifetime();
954 enum DestructionKind {
957 DK_objc_strong_lifetime,
958 DK_objc_weak_lifetime
961 /// isDestructedType - nonzero if objects of this type require
962 /// non-trivial work to clean up after. Non-zero because it's
963 /// conceivable that qualifiers (objc_gc(weak)?) could make
964 /// something require destruction.
965 DestructionKind isDestructedType() const {
966 return isDestructedTypeImpl(*this);
969 /// \brief Determine whether expressions of the given type are forbidden
970 /// from being lvalues in C.
972 /// The expression types that are forbidden to be lvalues are:
973 /// - 'void', but not qualified void
976 /// The exact rule here is C99 6.3.2.1:
977 /// An lvalue is an expression with an object type or an incomplete
978 /// type other than void.
979 bool isCForbiddenLValueType() const;
982 // These methods are implemented in a separate translation unit;
983 // "static"-ize them to avoid creating temporary QualTypes in the
985 static bool isConstant(QualType T, ASTContext& Ctx);
986 static QualType getDesugaredType(QualType T, const ASTContext &Context);
987 static SplitQualType getSplitDesugaredType(QualType T);
988 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
989 static QualType getSingleStepDesugaredTypeImpl(QualType type,
990 const ASTContext &C);
991 static QualType IgnoreParens(QualType T);
992 static DestructionKind isDestructedTypeImpl(QualType type);
998 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
999 /// to a specific Type class.
1000 template<> struct simplify_type< ::clang::QualType> {
1001 typedef const ::clang::Type *SimpleType;
1002 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1003 return Val.getTypePtr();
1007 // Teach SmallPtrSet that QualType is "basically a pointer".
1009 class PointerLikeTypeTraits<clang::QualType> {
1011 static inline void *getAsVoidPointer(clang::QualType P) {
1012 return P.getAsOpaquePtr();
1014 static inline clang::QualType getFromVoidPointer(void *P) {
1015 return clang::QualType::getFromOpaquePtr(P);
1017 // Various qualifiers go in low bits.
1018 enum { NumLowBitsAvailable = 0 };
1021 } // end namespace llvm
1025 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1026 /// classes, which allows \c QualType to access the common fields between the
1029 class ExtQualsTypeCommonBase {
1030 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1031 : BaseType(baseType), CanonicalType(canon) {}
1033 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1034 /// a self-referential pointer (for \c Type).
1036 /// This pointer allows an efficient mapping from a QualType to its
1037 /// underlying type pointer.
1038 const Type *const BaseType;
1040 /// \brief The canonical type of this type. A QualType.
1041 QualType CanonicalType;
1043 friend class QualType;
1045 friend class ExtQuals;
1048 /// ExtQuals - We can encode up to four bits in the low bits of a
1049 /// type pointer, but there are many more type qualifiers that we want
1050 /// to be able to apply to an arbitrary type. Therefore we have this
1051 /// struct, intended to be heap-allocated and used by QualType to
1052 /// store qualifiers.
1054 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1055 /// in three low bits on the QualType pointer; a fourth bit records whether
1056 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1057 /// Objective-C GC attributes) are much more rare.
1058 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1059 // NOTE: changing the fast qualifiers should be straightforward as
1060 // long as you don't make 'const' non-fast.
1062 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1063 // Fast qualifiers must occupy the low-order bits.
1064 // b) Update Qualifiers::FastWidth and FastMask.
1066 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1067 // b) Update remove{Volatile,Restrict}, defined near the end of
1070 // a) Update get{Volatile,Restrict}Type.
1072 /// Quals - the immutable set of qualifiers applied by this
1073 /// node; always contains extended qualifiers.
1076 ExtQuals *this_() { return this; }
1079 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1080 : ExtQualsTypeCommonBase(baseType,
1081 canon.isNull() ? QualType(this_(), 0) : canon),
1084 assert(Quals.hasNonFastQualifiers()
1085 && "ExtQuals created with no fast qualifiers");
1086 assert(!Quals.hasFastQualifiers()
1087 && "ExtQuals created with fast qualifiers");
1090 Qualifiers getQualifiers() const { return Quals; }
1092 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1093 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1095 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1096 Qualifiers::ObjCLifetime getObjCLifetime() const {
1097 return Quals.getObjCLifetime();
1100 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1101 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1103 const Type *getBaseType() const { return BaseType; }
1106 void Profile(llvm::FoldingSetNodeID &ID) const {
1107 Profile(ID, getBaseType(), Quals);
1109 static void Profile(llvm::FoldingSetNodeID &ID,
1110 const Type *BaseType,
1112 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1113 ID.AddPointer(BaseType);
1118 /// \brief The kind of C++0x ref-qualifier associated with a function type,
1119 /// which determines whether a member function's "this" object can be an
1120 /// lvalue, rvalue, or neither.
1121 enum RefQualifierKind {
1122 /// \brief No ref-qualifier was provided.
1124 /// \brief An lvalue ref-qualifier was provided (\c &).
1126 /// \brief An rvalue ref-qualifier was provided (\c &&).
1130 /// Type - This is the base class of the type hierarchy. A central concept
1131 /// with types is that each type always has a canonical type. A canonical type
1132 /// is the type with any typedef names stripped out of it or the types it
1133 /// references. For example, consider:
1135 /// typedef int foo;
1136 /// typedef foo* bar;
1137 /// 'int *' 'foo *' 'bar'
1139 /// There will be a Type object created for 'int'. Since int is canonical, its
1140 /// canonicaltype pointer points to itself. There is also a Type for 'foo' (a
1141 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1142 /// there is a PointerType that represents 'int*', which, like 'int', is
1143 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1144 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1147 /// Non-canonical types are useful for emitting diagnostics, without losing
1148 /// information about typedefs being used. Canonical types are useful for type
1149 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1150 /// about whether something has a particular form (e.g. is a function type),
1151 /// because they implicitly, recursively, strip all typedefs out of a type.
1153 /// Types, once created, are immutable.
1155 class Type : public ExtQualsTypeCommonBase {
1158 #define TYPE(Class, Base) Class,
1159 #define LAST_TYPE(Class) TypeLast = Class,
1160 #define ABSTRACT_TYPE(Class, Base)
1161 #include "clang/AST/TypeNodes.def"
1162 TagFirst = Record, TagLast = Enum
1166 Type(const Type &) LLVM_DELETED_FUNCTION;
1167 void operator=(const Type &) LLVM_DELETED_FUNCTION;
1169 /// Bitfields required by the Type class.
1170 class TypeBitfields {
1172 template <class T> friend class TypePropertyCache;
1174 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1177 /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1178 unsigned Dependent : 1;
1180 /// \brief Whether this type somehow involves a template parameter, even
1181 /// if the resolution of the type does not depend on a template parameter.
1182 unsigned InstantiationDependent : 1;
1184 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1185 unsigned VariablyModified : 1;
1187 /// \brief Whether this type contains an unexpanded parameter pack
1188 /// (for C++0x variadic templates).
1189 unsigned ContainsUnexpandedParameterPack : 1;
1191 /// \brief True if the cache (i.e. the bitfields here starting with
1192 /// 'Cache') is valid.
1193 mutable unsigned CacheValid : 1;
1195 /// \brief Linkage of this type.
1196 mutable unsigned CachedLinkage : 3;
1198 /// \brief Whether this type involves and local or unnamed types.
1199 mutable unsigned CachedLocalOrUnnamed : 1;
1201 /// \brief FromAST - Whether this type comes from an AST file.
1202 mutable unsigned FromAST : 1;
1204 bool isCacheValid() const {
1207 Linkage getLinkage() const {
1208 assert(isCacheValid() && "getting linkage from invalid cache");
1209 return static_cast<Linkage>(CachedLinkage);
1211 bool hasLocalOrUnnamedType() const {
1212 assert(isCacheValid() && "getting linkage from invalid cache");
1213 return CachedLocalOrUnnamed;
1216 enum { NumTypeBits = 18 };
1219 // These classes allow subclasses to somewhat cleanly pack bitfields
1222 class ArrayTypeBitfields {
1223 friend class ArrayType;
1225 unsigned : NumTypeBits;
1227 /// IndexTypeQuals - CVR qualifiers from declarations like
1228 /// 'int X[static restrict 4]'. For function parameters only.
1229 unsigned IndexTypeQuals : 3;
1231 /// SizeModifier - storage class qualifiers from declarations like
1232 /// 'int X[static restrict 4]'. For function parameters only.
1233 /// Actually an ArrayType::ArraySizeModifier.
1234 unsigned SizeModifier : 3;
1237 class BuiltinTypeBitfields {
1238 friend class BuiltinType;
1240 unsigned : NumTypeBits;
1242 /// The kind (BuiltinType::Kind) of builtin type this is.
1246 class FunctionTypeBitfields {
1247 friend class FunctionType;
1249 unsigned : NumTypeBits;
1251 /// Extra information which affects how the function is called, like
1252 /// regparm and the calling convention.
1253 unsigned ExtInfo : 9;
1255 /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1256 /// other bitfields.
1257 /// The qualifiers are part of FunctionProtoType because...
1259 /// C++ 8.3.5p4: The return type, the parameter type list and the
1260 /// cv-qualifier-seq, [...], are part of the function type.
1261 unsigned TypeQuals : 3;
1264 class ObjCObjectTypeBitfields {
1265 friend class ObjCObjectType;
1267 unsigned : NumTypeBits;
1269 /// NumProtocols - The number of protocols stored directly on this
1271 unsigned NumProtocols : 32 - NumTypeBits;
1274 class ReferenceTypeBitfields {
1275 friend class ReferenceType;
1277 unsigned : NumTypeBits;
1279 /// True if the type was originally spelled with an lvalue sigil.
1280 /// This is never true of rvalue references but can also be false
1281 /// on lvalue references because of C++0x [dcl.typedef]p9,
1284 /// typedef int &ref; // lvalue, spelled lvalue
1285 /// typedef int &&rvref; // rvalue
1286 /// ref &a; // lvalue, inner ref, spelled lvalue
1287 /// ref &&a; // lvalue, inner ref
1288 /// rvref &a; // lvalue, inner ref, spelled lvalue
1289 /// rvref &&a; // rvalue, inner ref
1290 unsigned SpelledAsLValue : 1;
1292 /// True if the inner type is a reference type. This only happens
1293 /// in non-canonical forms.
1294 unsigned InnerRef : 1;
1297 class TypeWithKeywordBitfields {
1298 friend class TypeWithKeyword;
1300 unsigned : NumTypeBits;
1302 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1303 unsigned Keyword : 8;
1306 class VectorTypeBitfields {
1307 friend class VectorType;
1309 unsigned : NumTypeBits;
1311 /// VecKind - The kind of vector, either a generic vector type or some
1312 /// target-specific vector type such as for AltiVec or Neon.
1313 unsigned VecKind : 3;
1315 /// NumElements - The number of elements in the vector.
1316 unsigned NumElements : 29 - NumTypeBits;
1318 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1321 class AttributedTypeBitfields {
1322 friend class AttributedType;
1324 unsigned : NumTypeBits;
1326 /// AttrKind - an AttributedType::Kind
1327 unsigned AttrKind : 32 - NumTypeBits;
1330 class AutoTypeBitfields {
1331 friend class AutoType;
1333 unsigned : NumTypeBits;
1335 /// Was this placeholder type spelled as 'decltype(auto)'?
1336 unsigned IsDecltypeAuto : 1;
1340 TypeBitfields TypeBits;
1341 ArrayTypeBitfields ArrayTypeBits;
1342 AttributedTypeBitfields AttributedTypeBits;
1343 AutoTypeBitfields AutoTypeBits;
1344 BuiltinTypeBitfields BuiltinTypeBits;
1345 FunctionTypeBitfields FunctionTypeBits;
1346 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1347 ReferenceTypeBitfields ReferenceTypeBits;
1348 TypeWithKeywordBitfields TypeWithKeywordBits;
1349 VectorTypeBitfields VectorTypeBits;
1353 /// \brief Set whether this type comes from an AST file.
1354 void setFromAST(bool V = true) const {
1355 TypeBits.FromAST = V;
1358 template <class T> friend class TypePropertyCache;
1361 // silence VC++ warning C4355: 'this' : used in base member initializer list
1362 Type *this_() { return this; }
1363 Type(TypeClass tc, QualType canon, bool Dependent,
1364 bool InstantiationDependent, bool VariablyModified,
1365 bool ContainsUnexpandedParameterPack)
1366 : ExtQualsTypeCommonBase(this,
1367 canon.isNull() ? QualType(this_(), 0) : canon) {
1369 TypeBits.Dependent = Dependent;
1370 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1371 TypeBits.VariablyModified = VariablyModified;
1372 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1373 TypeBits.CacheValid = false;
1374 TypeBits.CachedLocalOrUnnamed = false;
1375 TypeBits.CachedLinkage = NoLinkage;
1376 TypeBits.FromAST = false;
1378 friend class ASTContext;
1380 void setDependent(bool D = true) {
1381 TypeBits.Dependent = D;
1383 TypeBits.InstantiationDependent = true;
1385 void setInstantiationDependent(bool D = true) {
1386 TypeBits.InstantiationDependent = D; }
1387 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1389 void setContainsUnexpandedParameterPack(bool PP = true) {
1390 TypeBits.ContainsUnexpandedParameterPack = PP;
1394 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1396 /// \brief Whether this type comes from an AST file.
1397 bool isFromAST() const { return TypeBits.FromAST; }
1399 /// \brief Whether this type is or contains an unexpanded parameter
1400 /// pack, used to support C++0x variadic templates.
1402 /// A type that contains a parameter pack shall be expanded by the
1403 /// ellipsis operator at some point. For example, the typedef in the
1404 /// following example contains an unexpanded parameter pack 'T':
1407 /// template<typename ...T>
1409 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1413 /// Note that this routine does not specify which
1414 bool containsUnexpandedParameterPack() const {
1415 return TypeBits.ContainsUnexpandedParameterPack;
1418 /// Determines if this type would be canonical if it had no further
1420 bool isCanonicalUnqualified() const {
1421 return CanonicalType == QualType(this, 0);
1424 /// Pull a single level of sugar off of this locally-unqualified type.
1425 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1426 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1427 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1429 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1430 /// object types, function types, and incomplete types.
1432 /// isIncompleteType - Return true if this is an incomplete type.
1433 /// A type that can describe objects, but which lacks information needed to
1434 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1435 /// routine will need to determine if the size is actually required.
1437 /// \brief Def If non-NULL, and the type refers to some kind of declaration
1438 /// that can be completed (such as a C struct, C++ class, or Objective-C
1439 /// class), will be set to the declaration.
1440 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1442 /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1443 /// type, in other words, not a function type.
1444 bool isIncompleteOrObjectType() const {
1445 return !isFunctionType();
1448 /// \brief Determine whether this type is an object type.
1449 bool isObjectType() const {
1450 // C++ [basic.types]p8:
1451 // An object type is a (possibly cv-qualified) type that is not a
1452 // function type, not a reference type, and not a void type.
1453 return !isReferenceType() && !isFunctionType() && !isVoidType();
1456 /// isLiteralType - Return true if this is a literal type
1457 /// (C++11 [basic.types]p10)
1458 bool isLiteralType(const ASTContext &Ctx) const;
1460 /// \brief Test if this type is a standard-layout type.
1461 /// (C++0x [basic.type]p9)
1462 bool isStandardLayoutType() const;
1464 /// Helper methods to distinguish type categories. All type predicates
1465 /// operate on the canonical type, ignoring typedefs and qualifiers.
1467 /// isBuiltinType - returns true if the type is a builtin type.
1468 bool isBuiltinType() const;
1470 /// isSpecificBuiltinType - Test for a particular builtin type.
1471 bool isSpecificBuiltinType(unsigned K) const;
1473 /// isPlaceholderType - Test for a type which does not represent an
1474 /// actual type-system type but is instead used as a placeholder for
1475 /// various convenient purposes within Clang. All such types are
1477 bool isPlaceholderType() const;
1478 const BuiltinType *getAsPlaceholderType() const;
1480 /// isSpecificPlaceholderType - Test for a specific placeholder type.
1481 bool isSpecificPlaceholderType(unsigned K) const;
1483 /// isNonOverloadPlaceholderType - Test for a placeholder type
1484 /// other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
1485 bool isNonOverloadPlaceholderType() const;
1487 /// isIntegerType() does *not* include complex integers (a GCC extension).
1488 /// isComplexIntegerType() can be used to test for complex integers.
1489 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1490 bool isEnumeralType() const;
1491 bool isBooleanType() const;
1492 bool isCharType() const;
1493 bool isWideCharType() const;
1494 bool isChar16Type() const;
1495 bool isChar32Type() const;
1496 bool isAnyCharacterType() const;
1497 bool isIntegralType(ASTContext &Ctx) const;
1499 /// \brief Determine whether this type is an integral or enumeration type.
1500 bool isIntegralOrEnumerationType() const;
1501 /// \brief Determine whether this type is an integral or unscoped enumeration
1503 bool isIntegralOrUnscopedEnumerationType() const;
1505 /// Floating point categories.
1506 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1507 /// isComplexType() does *not* include complex integers (a GCC extension).
1508 /// isComplexIntegerType() can be used to test for complex integers.
1509 bool isComplexType() const; // C99 6.2.5p11 (complex)
1510 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1511 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1512 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1513 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1514 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1515 bool isVoidType() const; // C99 6.2.5p19
1516 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1517 bool isAggregateType() const;
1518 bool isFundamentalType() const;
1519 bool isCompoundType() const;
1521 // Type Predicates: Check to see if this type is structurally the specified
1522 // type, ignoring typedefs and qualifiers.
1523 bool isFunctionType() const;
1524 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1525 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1526 bool isPointerType() const;
1527 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1528 bool isBlockPointerType() const;
1529 bool isVoidPointerType() const;
1530 bool isReferenceType() const;
1531 bool isLValueReferenceType() const;
1532 bool isRValueReferenceType() const;
1533 bool isFunctionPointerType() const;
1534 bool isMemberPointerType() const;
1535 bool isMemberFunctionPointerType() const;
1536 bool isMemberDataPointerType() const;
1537 bool isArrayType() const;
1538 bool isConstantArrayType() const;
1539 bool isIncompleteArrayType() const;
1540 bool isVariableArrayType() const;
1541 bool isDependentSizedArrayType() const;
1542 bool isRecordType() const;
1543 bool isClassType() const;
1544 bool isStructureType() const;
1545 bool isInterfaceType() const;
1546 bool isStructureOrClassType() const;
1547 bool isUnionType() const;
1548 bool isComplexIntegerType() const; // GCC _Complex integer type.
1549 bool isVectorType() const; // GCC vector type.
1550 bool isExtVectorType() const; // Extended vector type.
1551 bool isObjCObjectPointerType() const; // pointer to ObjC object
1552 bool isObjCRetainableType() const; // ObjC object or block pointer
1553 bool isObjCLifetimeType() const; // (array of)* retainable type
1554 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1555 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1556 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1557 // for the common case.
1558 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1559 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1560 bool isObjCQualifiedIdType() const; // id<foo>
1561 bool isObjCQualifiedClassType() const; // Class<foo>
1562 bool isObjCObjectOrInterfaceType() const;
1563 bool isObjCIdType() const; // id
1564 bool isObjCClassType() const; // Class
1565 bool isObjCSelType() const; // Class
1566 bool isObjCBuiltinType() const; // 'id' or 'Class'
1567 bool isObjCARCBridgableType() const;
1568 bool isCARCBridgableType() const;
1569 bool isTemplateTypeParmType() const; // C++ template type parameter
1570 bool isNullPtrType() const; // C++0x nullptr_t
1571 bool isAtomicType() const; // C11 _Atomic()
1573 bool isImage1dT() const; // OpenCL image1d_t
1574 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1575 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1576 bool isImage2dT() const; // OpenCL image2d_t
1577 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1578 bool isImage3dT() const; // OpenCL image3d_t
1580 bool isImageType() const; // Any OpenCL image type
1582 bool isSamplerT() const; // OpenCL sampler_t
1583 bool isEventT() const; // OpenCL event_t
1585 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1587 /// Determines if this type, which must satisfy
1588 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1589 /// than implicitly __strong.
1590 bool isObjCARCImplicitlyUnretainedType() const;
1592 /// Return the implicit lifetime for this type, which must not be dependent.
1593 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1595 enum ScalarTypeKind {
1598 STK_ObjCObjectPointer,
1603 STK_IntegralComplex,
1606 /// getScalarTypeKind - Given that this is a scalar type, classify it.
1607 ScalarTypeKind getScalarTypeKind() const;
1609 /// isDependentType - Whether this type is a dependent type, meaning
1610 /// that its definition somehow depends on a template parameter
1611 /// (C++ [temp.dep.type]).
1612 bool isDependentType() const { return TypeBits.Dependent; }
1614 /// \brief Determine whether this type is an instantiation-dependent type,
1615 /// meaning that the type involves a template parameter (even if the
1616 /// definition does not actually depend on the type substituted for that
1617 /// template parameter).
1618 bool isInstantiationDependentType() const {
1619 return TypeBits.InstantiationDependent;
1622 /// \brief Determine whether this type is an undeduced type, meaning that
1623 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1624 bool isUndeducedType() const;
1626 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1627 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1629 /// \brief Whether this type involves a variable-length array type
1630 /// with a definite size.
1631 bool hasSizedVLAType() const;
1633 /// \brief Whether this type is or contains a local or unnamed type.
1634 bool hasUnnamedOrLocalType() const;
1636 bool isOverloadableType() const;
1638 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1639 bool isElaboratedTypeSpecifier() const;
1641 bool canDecayToPointerType() const;
1643 /// hasPointerRepresentation - Whether this type is represented
1644 /// natively as a pointer; this includes pointers, references, block
1645 /// pointers, and Objective-C interface, qualified id, and qualified
1646 /// interface types, as well as nullptr_t.
1647 bool hasPointerRepresentation() const;
1649 /// hasObjCPointerRepresentation - Whether this type can represent
1650 /// an objective pointer type for the purpose of GC'ability
1651 bool hasObjCPointerRepresentation() const;
1653 /// \brief Determine whether this type has an integer representation
1654 /// of some sort, e.g., it is an integer type or a vector.
1655 bool hasIntegerRepresentation() const;
1657 /// \brief Determine whether this type has an signed integer representation
1658 /// of some sort, e.g., it is an signed integer type or a vector.
1659 bool hasSignedIntegerRepresentation() const;
1661 /// \brief Determine whether this type has an unsigned integer representation
1662 /// of some sort, e.g., it is an unsigned integer type or a vector.
1663 bool hasUnsignedIntegerRepresentation() const;
1665 /// \brief Determine whether this type has a floating-point representation
1666 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1667 bool hasFloatingRepresentation() const;
1669 // Type Checking Functions: Check to see if this type is structurally the
1670 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1671 // the best type we can.
1672 const RecordType *getAsStructureType() const;
1673 /// NOTE: getAs*ArrayType are methods on ASTContext.
1674 const RecordType *getAsUnionType() const;
1675 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1676 // The following is a convenience method that returns an ObjCObjectPointerType
1677 // for object declared using an interface.
1678 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1679 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1680 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1681 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1683 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1684 /// because the type is a RecordType or because it is the injected-class-name
1685 /// type of a class template or class template partial specialization.
1686 CXXRecordDecl *getAsCXXRecordDecl() const;
1688 /// If this is a pointer or reference to a RecordType, return the
1689 /// CXXRecordDecl that that type refers to.
1691 /// If this is not a pointer or reference, or the type being pointed to does
1692 /// not refer to a CXXRecordDecl, returns NULL.
1693 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1695 /// \brief Get the AutoType whose type will be deduced for a variable with
1696 /// an initializer of this type. This looks through declarators like pointer
1697 /// types, but not through decltype or typedefs.
1698 AutoType *getContainedAutoType() const;
1700 /// Member-template getAs<specific type>'. Look through sugar for
1701 /// an instance of \<specific type>. This scheme will eventually
1702 /// replace the specific getAsXXXX methods above.
1704 /// There are some specializations of this member template listed
1705 /// immediately following this class.
1706 template <typename T> const T *getAs() const;
1708 /// A variant of getAs<> for array types which silently discards
1709 /// qualifiers from the outermost type.
1710 const ArrayType *getAsArrayTypeUnsafe() const;
1712 /// Member-template castAs<specific type>. Look through sugar for
1713 /// the underlying instance of \<specific type>.
1715 /// This method has the same relationship to getAs<T> as cast<T> has
1716 /// to dyn_cast<T>; which is to say, the underlying type *must*
1717 /// have the intended type, and this method will never return null.
1718 template <typename T> const T *castAs() const;
1720 /// A variant of castAs<> for array type which silently discards
1721 /// qualifiers from the outermost type.
1722 const ArrayType *castAsArrayTypeUnsafe() const;
1724 /// getBaseElementTypeUnsafe - Get the base element type of this
1725 /// type, potentially discarding type qualifiers. This method
1726 /// should never be used when type qualifiers are meaningful.
1727 const Type *getBaseElementTypeUnsafe() const;
1729 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1730 /// element type of the array, potentially with type qualifiers missing.
1731 /// This method should never be used when type qualifiers are meaningful.
1732 const Type *getArrayElementTypeNoTypeQual() const;
1734 /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1735 /// pointer, this returns the respective pointee.
1736 QualType getPointeeType() const;
1738 /// getUnqualifiedDesugaredType() - Return the specified type with
1739 /// any "sugar" removed from the type, removing any typedefs,
1740 /// typeofs, etc., as well as any qualifiers.
1741 const Type *getUnqualifiedDesugaredType() const;
1743 /// More type predicates useful for type checking/promotion
1744 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1746 /// isSignedIntegerType - Return true if this is an integer type that is
1747 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1748 /// or an enum decl which has a signed representation.
1749 bool isSignedIntegerType() const;
1751 /// isUnsignedIntegerType - Return true if this is an integer type that is
1752 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1753 /// or an enum decl which has an unsigned representation.
1754 bool isUnsignedIntegerType() const;
1756 /// Determines whether this is an integer type that is signed or an
1757 /// enumeration types whose underlying type is a signed integer type.
1758 bool isSignedIntegerOrEnumerationType() const;
1760 /// Determines whether this is an integer type that is unsigned or an
1761 /// enumeration types whose underlying type is a unsigned integer type.
1762 bool isUnsignedIntegerOrEnumerationType() const;
1764 /// isConstantSizeType - Return true if this is not a variable sized type,
1765 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1766 /// incomplete types.
1767 bool isConstantSizeType() const;
1769 /// isSpecifierType - Returns true if this type can be represented by some
1770 /// set of type specifiers.
1771 bool isSpecifierType() const;
1773 /// \brief Determine the linkage of this type.
1774 Linkage getLinkage() const;
1776 /// \brief Determine the visibility of this type.
1777 Visibility getVisibility() const {
1778 return getLinkageAndVisibility().getVisibility();
1781 /// \brief Return true if the visibility was explicitly set is the code.
1782 bool isVisibilityExplicit() const {
1783 return getLinkageAndVisibility().isVisibilityExplicit();
1786 /// \brief Determine the linkage and visibility of this type.
1787 LinkageInfo getLinkageAndVisibility() const;
1789 /// \brief True if the computed linkage is valid. Used for consistency
1790 /// checking. Should always return true.
1791 bool isLinkageValid() const;
1793 const char *getTypeClassName() const;
1795 QualType getCanonicalTypeInternal() const {
1796 return CanonicalType;
1798 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1801 friend class ASTReader;
1802 friend class ASTWriter;
1805 /// \brief This will check for a TypedefType by removing any existing sugar
1806 /// until it reaches a TypedefType or a non-sugared type.
1807 template <> const TypedefType *Type::getAs() const;
1809 /// \brief This will check for a TemplateSpecializationType by removing any
1810 /// existing sugar until it reaches a TemplateSpecializationType or a
1811 /// non-sugared type.
1812 template <> const TemplateSpecializationType *Type::getAs() const;
1814 /// \brief This will check for an AttributedType by removing any existing sugar
1815 /// until it reaches an AttributedType or a non-sugared type.
1816 template <> const AttributedType *Type::getAs() const;
1818 // We can do canonical leaf types faster, because we don't have to
1819 // worry about preserving child type decoration.
1820 #define TYPE(Class, Base)
1821 #define LEAF_TYPE(Class) \
1822 template <> inline const Class##Type *Type::getAs() const { \
1823 return dyn_cast<Class##Type>(CanonicalType); \
1825 template <> inline const Class##Type *Type::castAs() const { \
1826 return cast<Class##Type>(CanonicalType); \
1828 #include "clang/AST/TypeNodes.def"
1831 /// BuiltinType - This class is used for builtin types like 'int'. Builtin
1832 /// types are always canonical and have a literal name field.
1833 class BuiltinType : public Type {
1836 #define BUILTIN_TYPE(Id, SingletonId) Id,
1837 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
1838 #include "clang/AST/BuiltinTypes.def"
1843 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1844 /*InstantiationDependent=*/(K == Dependent),
1845 /*VariablyModified=*/false,
1846 /*Unexpanded paramter pack=*/false) {
1847 BuiltinTypeBits.Kind = K;
1850 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1851 StringRef getName(const PrintingPolicy &Policy) const;
1852 const char *getNameAsCString(const PrintingPolicy &Policy) const {
1853 // The StringRef is null-terminated.
1854 StringRef str = getName(Policy);
1855 assert(!str.empty() && str.data()[str.size()] == '\0');
1859 bool isSugared() const { return false; }
1860 QualType desugar() const { return QualType(this, 0); }
1862 bool isInteger() const {
1863 return getKind() >= Bool && getKind() <= Int128;
1866 bool isSignedInteger() const {
1867 return getKind() >= Char_S && getKind() <= Int128;
1870 bool isUnsignedInteger() const {
1871 return getKind() >= Bool && getKind() <= UInt128;
1874 bool isFloatingPoint() const {
1875 return getKind() >= Half && getKind() <= LongDouble;
1878 /// Determines whether the given kind corresponds to a placeholder type.
1879 static bool isPlaceholderTypeKind(Kind K) {
1880 return K >= Overload;
1883 /// Determines whether this type is a placeholder type, i.e. a type
1884 /// which cannot appear in arbitrary positions in a fully-formed
1886 bool isPlaceholderType() const {
1887 return isPlaceholderTypeKind(getKind());
1890 /// Determines whether this type is a placeholder type other than
1891 /// Overload. Most placeholder types require only syntactic
1892 /// information about their context in order to be resolved (e.g.
1893 /// whether it is a call expression), which means they can (and
1894 /// should) be resolved in an earlier "phase" of analysis.
1895 /// Overload expressions sometimes pick up further information
1896 /// from their context, like whether the context expects a
1897 /// specific function-pointer type, and so frequently need
1898 /// special treatment.
1899 bool isNonOverloadPlaceholderType() const {
1900 return getKind() > Overload;
1903 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1906 /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex
1907 /// types (_Complex float etc) as well as the GCC integer complex extensions.
1909 class ComplexType : public Type, public llvm::FoldingSetNode {
1910 QualType ElementType;
1911 ComplexType(QualType Element, QualType CanonicalPtr) :
1912 Type(Complex, CanonicalPtr, Element->isDependentType(),
1913 Element->isInstantiationDependentType(),
1914 Element->isVariablyModifiedType(),
1915 Element->containsUnexpandedParameterPack()),
1916 ElementType(Element) {
1918 friend class ASTContext; // ASTContext creates these.
1921 QualType getElementType() const { return ElementType; }
1923 bool isSugared() const { return false; }
1924 QualType desugar() const { return QualType(this, 0); }
1926 void Profile(llvm::FoldingSetNodeID &ID) {
1927 Profile(ID, getElementType());
1929 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1930 ID.AddPointer(Element.getAsOpaquePtr());
1933 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1936 /// ParenType - Sugar for parentheses used when specifying types.
1938 class ParenType : public Type, public llvm::FoldingSetNode {
1941 ParenType(QualType InnerType, QualType CanonType) :
1942 Type(Paren, CanonType, InnerType->isDependentType(),
1943 InnerType->isInstantiationDependentType(),
1944 InnerType->isVariablyModifiedType(),
1945 InnerType->containsUnexpandedParameterPack()),
1948 friend class ASTContext; // ASTContext creates these.
1952 QualType getInnerType() const { return Inner; }
1954 bool isSugared() const { return true; }
1955 QualType desugar() const { return getInnerType(); }
1957 void Profile(llvm::FoldingSetNodeID &ID) {
1958 Profile(ID, getInnerType());
1960 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1964 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1967 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
1969 class PointerType : public Type, public llvm::FoldingSetNode {
1970 QualType PointeeType;
1972 PointerType(QualType Pointee, QualType CanonicalPtr) :
1973 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1974 Pointee->isInstantiationDependentType(),
1975 Pointee->isVariablyModifiedType(),
1976 Pointee->containsUnexpandedParameterPack()),
1977 PointeeType(Pointee) {
1979 friend class ASTContext; // ASTContext creates these.
1983 QualType getPointeeType() const { return PointeeType; }
1985 bool isSugared() const { return false; }
1986 QualType desugar() const { return QualType(this, 0); }
1988 void Profile(llvm::FoldingSetNodeID &ID) {
1989 Profile(ID, getPointeeType());
1991 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1992 ID.AddPointer(Pointee.getAsOpaquePtr());
1995 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1998 /// \brief Represents a type which was implicitly adjusted by the semantic
1999 /// engine for arbitrary reasons. For example, array and function types can
2000 /// decay, and function types can have their calling conventions adjusted.
2001 class AdjustedType : public Type, public llvm::FoldingSetNode {
2002 QualType OriginalTy;
2003 QualType AdjustedTy;
2006 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2007 QualType CanonicalPtr)
2008 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2009 OriginalTy->isInstantiationDependentType(),
2010 OriginalTy->isVariablyModifiedType(),
2011 OriginalTy->containsUnexpandedParameterPack()),
2012 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2014 friend class ASTContext; // ASTContext creates these.
2017 QualType getOriginalType() const { return OriginalTy; }
2018 QualType getAdjustedType() const { return AdjustedTy; }
2020 bool isSugared() const { return true; }
2021 QualType desugar() const { return AdjustedTy; }
2023 void Profile(llvm::FoldingSetNodeID &ID) {
2024 Profile(ID, OriginalTy, AdjustedTy);
2026 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2027 ID.AddPointer(Orig.getAsOpaquePtr());
2028 ID.AddPointer(New.getAsOpaquePtr());
2031 static bool classof(const Type *T) {
2032 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2036 /// \brief Represents a pointer type decayed from an array or function type.
2037 class DecayedType : public AdjustedType {
2039 DecayedType(QualType OriginalType, QualType DecayedPtr, QualType CanonicalPtr)
2040 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
2041 assert(isa<PointerType>(getAdjustedType()));
2044 friend class ASTContext; // ASTContext creates these.
2047 QualType getDecayedType() const { return getAdjustedType(); }
2049 QualType getPointeeType() const {
2050 return cast<PointerType>(getDecayedType())->getPointeeType();
2053 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2056 /// BlockPointerType - pointer to a block type.
2057 /// This type is to represent types syntactically represented as
2058 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2060 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2061 QualType PointeeType; // Block is some kind of pointer type
2062 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2063 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2064 Pointee->isInstantiationDependentType(),
2065 Pointee->isVariablyModifiedType(),
2066 Pointee->containsUnexpandedParameterPack()),
2067 PointeeType(Pointee) {
2069 friend class ASTContext; // ASTContext creates these.
2073 // Get the pointee type. Pointee is required to always be a function type.
2074 QualType getPointeeType() const { return PointeeType; }
2076 bool isSugared() const { return false; }
2077 QualType desugar() const { return QualType(this, 0); }
2079 void Profile(llvm::FoldingSetNodeID &ID) {
2080 Profile(ID, getPointeeType());
2082 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2083 ID.AddPointer(Pointee.getAsOpaquePtr());
2086 static bool classof(const Type *T) {
2087 return T->getTypeClass() == BlockPointer;
2091 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
2093 class ReferenceType : public Type, public llvm::FoldingSetNode {
2094 QualType PointeeType;
2097 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2098 bool SpelledAsLValue) :
2099 Type(tc, CanonicalRef, Referencee->isDependentType(),
2100 Referencee->isInstantiationDependentType(),
2101 Referencee->isVariablyModifiedType(),
2102 Referencee->containsUnexpandedParameterPack()),
2103 PointeeType(Referencee)
2105 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2106 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2110 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2111 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2113 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2114 QualType getPointeeType() const {
2115 // FIXME: this might strip inner qualifiers; okay?
2116 const ReferenceType *T = this;
2117 while (T->isInnerRef())
2118 T = T->PointeeType->castAs<ReferenceType>();
2119 return T->PointeeType;
2122 void Profile(llvm::FoldingSetNodeID &ID) {
2123 Profile(ID, PointeeType, isSpelledAsLValue());
2125 static void Profile(llvm::FoldingSetNodeID &ID,
2126 QualType Referencee,
2127 bool SpelledAsLValue) {
2128 ID.AddPointer(Referencee.getAsOpaquePtr());
2129 ID.AddBoolean(SpelledAsLValue);
2132 static bool classof(const Type *T) {
2133 return T->getTypeClass() == LValueReference ||
2134 T->getTypeClass() == RValueReference;
2138 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
2140 class LValueReferenceType : public ReferenceType {
2141 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2142 bool SpelledAsLValue) :
2143 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2145 friend class ASTContext; // ASTContext creates these
2147 bool isSugared() const { return false; }
2148 QualType desugar() const { return QualType(this, 0); }
2150 static bool classof(const Type *T) {
2151 return T->getTypeClass() == LValueReference;
2155 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
2157 class RValueReferenceType : public ReferenceType {
2158 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2159 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2161 friend class ASTContext; // ASTContext creates these
2163 bool isSugared() const { return false; }
2164 QualType desugar() const { return QualType(this, 0); }
2166 static bool classof(const Type *T) {
2167 return T->getTypeClass() == RValueReference;
2171 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2173 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2174 QualType PointeeType;
2175 /// The class of which the pointee is a member. Must ultimately be a
2176 /// RecordType, but could be a typedef or a template parameter too.
2179 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2180 Type(MemberPointer, CanonicalPtr,
2181 Cls->isDependentType() || Pointee->isDependentType(),
2182 (Cls->isInstantiationDependentType() ||
2183 Pointee->isInstantiationDependentType()),
2184 Pointee->isVariablyModifiedType(),
2185 (Cls->containsUnexpandedParameterPack() ||
2186 Pointee->containsUnexpandedParameterPack())),
2187 PointeeType(Pointee), Class(Cls) {
2189 friend class ASTContext; // ASTContext creates these.
2192 QualType getPointeeType() const { return PointeeType; }
2194 /// Returns true if the member type (i.e. the pointee type) is a
2195 /// function type rather than a data-member type.
2196 bool isMemberFunctionPointer() const {
2197 return PointeeType->isFunctionProtoType();
2200 /// Returns true if the member type (i.e. the pointee type) is a
2201 /// data type rather than a function type.
2202 bool isMemberDataPointer() const {
2203 return !PointeeType->isFunctionProtoType();
2206 const Type *getClass() const { return Class; }
2207 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2209 bool isSugared() const { return false; }
2210 QualType desugar() const { return QualType(this, 0); }
2212 void Profile(llvm::FoldingSetNodeID &ID) {
2213 Profile(ID, getPointeeType(), getClass());
2215 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2216 const Type *Class) {
2217 ID.AddPointer(Pointee.getAsOpaquePtr());
2218 ID.AddPointer(Class);
2221 static bool classof(const Type *T) {
2222 return T->getTypeClass() == MemberPointer;
2226 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2228 class ArrayType : public Type, public llvm::FoldingSetNode {
2230 /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2231 /// an array with a static size (e.g. int X[static 4]), or an array
2232 /// with a star size (e.g. int X[*]).
2233 /// 'static' is only allowed on function parameters.
2234 enum ArraySizeModifier {
2235 Normal, Static, Star
2238 /// ElementType - The element type of the array.
2239 QualType ElementType;
2242 // C++ [temp.dep.type]p1:
2243 // A type is dependent if it is...
2244 // - an array type constructed from any dependent type or whose
2245 // size is specified by a constant expression that is
2247 ArrayType(TypeClass tc, QualType et, QualType can,
2248 ArraySizeModifier sm, unsigned tq,
2249 bool ContainsUnexpandedParameterPack)
2250 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2251 et->isInstantiationDependentType() || tc == DependentSizedArray,
2252 (tc == VariableArray || et->isVariablyModifiedType()),
2253 ContainsUnexpandedParameterPack),
2255 ArrayTypeBits.IndexTypeQuals = tq;
2256 ArrayTypeBits.SizeModifier = sm;
2259 friend class ASTContext; // ASTContext creates these.
2262 QualType getElementType() const { return ElementType; }
2263 ArraySizeModifier getSizeModifier() const {
2264 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2266 Qualifiers getIndexTypeQualifiers() const {
2267 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2269 unsigned getIndexTypeCVRQualifiers() const {
2270 return ArrayTypeBits.IndexTypeQuals;
2273 static bool classof(const Type *T) {
2274 return T->getTypeClass() == ConstantArray ||
2275 T->getTypeClass() == VariableArray ||
2276 T->getTypeClass() == IncompleteArray ||
2277 T->getTypeClass() == DependentSizedArray;
2281 /// ConstantArrayType - This class represents the canonical version of
2282 /// C arrays with a specified constant size. For example, the canonical
2283 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2284 /// type is 'int' and the size is 404.
2285 class ConstantArrayType : public ArrayType {
2286 llvm::APInt Size; // Allows us to unique the type.
2288 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2289 ArraySizeModifier sm, unsigned tq)
2290 : ArrayType(ConstantArray, et, can, sm, tq,
2291 et->containsUnexpandedParameterPack()),
2294 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2295 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2296 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2298 friend class ASTContext; // ASTContext creates these.
2300 const llvm::APInt &getSize() const { return Size; }
2301 bool isSugared() const { return false; }
2302 QualType desugar() const { return QualType(this, 0); }
2305 /// \brief Determine the number of bits required to address a member of
2306 // an array with the given element type and number of elements.
2307 static unsigned getNumAddressingBits(ASTContext &Context,
2308 QualType ElementType,
2309 const llvm::APInt &NumElements);
2311 /// \brief Determine the maximum number of active bits that an array's size
2312 /// can require, which limits the maximum size of the array.
2313 static unsigned getMaxSizeBits(ASTContext &Context);
2315 void Profile(llvm::FoldingSetNodeID &ID) {
2316 Profile(ID, getElementType(), getSize(),
2317 getSizeModifier(), getIndexTypeCVRQualifiers());
2319 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2320 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2321 unsigned TypeQuals) {
2322 ID.AddPointer(ET.getAsOpaquePtr());
2323 ID.AddInteger(ArraySize.getZExtValue());
2324 ID.AddInteger(SizeMod);
2325 ID.AddInteger(TypeQuals);
2327 static bool classof(const Type *T) {
2328 return T->getTypeClass() == ConstantArray;
2332 /// IncompleteArrayType - This class represents C arrays with an unspecified
2333 /// size. For example 'int A[]' has an IncompleteArrayType where the element
2334 /// type is 'int' and the size is unspecified.
2335 class IncompleteArrayType : public ArrayType {
2337 IncompleteArrayType(QualType et, QualType can,
2338 ArraySizeModifier sm, unsigned tq)
2339 : ArrayType(IncompleteArray, et, can, sm, tq,
2340 et->containsUnexpandedParameterPack()) {}
2341 friend class ASTContext; // ASTContext creates these.
2343 bool isSugared() const { return false; }
2344 QualType desugar() const { return QualType(this, 0); }
2346 static bool classof(const Type *T) {
2347 return T->getTypeClass() == IncompleteArray;
2350 friend class StmtIteratorBase;
2352 void Profile(llvm::FoldingSetNodeID &ID) {
2353 Profile(ID, getElementType(), getSizeModifier(),
2354 getIndexTypeCVRQualifiers());
2357 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2358 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2359 ID.AddPointer(ET.getAsOpaquePtr());
2360 ID.AddInteger(SizeMod);
2361 ID.AddInteger(TypeQuals);
2365 /// VariableArrayType - This class represents C arrays with a specified size
2366 /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'.
2367 /// Since the size expression is an arbitrary expression, we store it as such.
2369 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2370 /// should not be: two lexically equivalent variable array types could mean
2371 /// different things, for example, these variables do not have the same type
2374 /// void foo(int x) {
2380 class VariableArrayType : public ArrayType {
2381 /// SizeExpr - An assignment expression. VLA's are only permitted within
2382 /// a function block.
2384 /// Brackets - The left and right array brackets.
2385 SourceRange Brackets;
2387 VariableArrayType(QualType et, QualType can, Expr *e,
2388 ArraySizeModifier sm, unsigned tq,
2389 SourceRange brackets)
2390 : ArrayType(VariableArray, et, can, sm, tq,
2391 et->containsUnexpandedParameterPack()),
2392 SizeExpr((Stmt*) e), Brackets(brackets) {}
2393 friend class ASTContext; // ASTContext creates these.
2396 Expr *getSizeExpr() const {
2397 // We use C-style casts instead of cast<> here because we do not wish
2398 // to have a dependency of Type.h on Stmt.h/Expr.h.
2399 return (Expr*) SizeExpr;
2401 SourceRange getBracketsRange() const { return Brackets; }
2402 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2403 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2405 bool isSugared() const { return false; }
2406 QualType desugar() const { return QualType(this, 0); }
2408 static bool classof(const Type *T) {
2409 return T->getTypeClass() == VariableArray;
2412 friend class StmtIteratorBase;
2414 void Profile(llvm::FoldingSetNodeID &ID) {
2415 llvm_unreachable("Cannot unique VariableArrayTypes.");
2419 /// DependentSizedArrayType - This type represents an array type in
2420 /// C++ whose size is a value-dependent expression. For example:
2423 /// template<typename T, int Size>
2429 /// For these types, we won't actually know what the array bound is
2430 /// until template instantiation occurs, at which point this will
2431 /// become either a ConstantArrayType or a VariableArrayType.
2432 class DependentSizedArrayType : public ArrayType {
2433 const ASTContext &Context;
2435 /// \brief An assignment expression that will instantiate to the
2436 /// size of the array.
2438 /// The expression itself might be NULL, in which case the array
2439 /// type will have its size deduced from an initializer.
2442 /// Brackets - The left and right array brackets.
2443 SourceRange Brackets;
2445 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2446 Expr *e, ArraySizeModifier sm, unsigned tq,
2447 SourceRange brackets);
2449 friend class ASTContext; // ASTContext creates these.
2452 Expr *getSizeExpr() const {
2453 // We use C-style casts instead of cast<> here because we do not wish
2454 // to have a dependency of Type.h on Stmt.h/Expr.h.
2455 return (Expr*) SizeExpr;
2457 SourceRange getBracketsRange() const { return Brackets; }
2458 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2459 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2461 bool isSugared() const { return false; }
2462 QualType desugar() const { return QualType(this, 0); }
2464 static bool classof(const Type *T) {
2465 return T->getTypeClass() == DependentSizedArray;
2468 friend class StmtIteratorBase;
2471 void Profile(llvm::FoldingSetNodeID &ID) {
2472 Profile(ID, Context, getElementType(),
2473 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2476 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2477 QualType ET, ArraySizeModifier SizeMod,
2478 unsigned TypeQuals, Expr *E);
2481 /// DependentSizedExtVectorType - This type represent an extended vector type
2482 /// where either the type or size is dependent. For example:
2484 /// template<typename T, int Size>
2486 /// typedef T __attribute__((ext_vector_type(Size))) type;
2489 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2490 const ASTContext &Context;
2492 /// ElementType - The element type of the array.
2493 QualType ElementType;
2496 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2497 QualType can, Expr *SizeExpr, SourceLocation loc);
2499 friend class ASTContext;
2502 Expr *getSizeExpr() const { return SizeExpr; }
2503 QualType getElementType() const { return ElementType; }
2504 SourceLocation getAttributeLoc() const { return loc; }
2506 bool isSugared() const { return false; }
2507 QualType desugar() const { return QualType(this, 0); }
2509 static bool classof(const Type *T) {
2510 return T->getTypeClass() == DependentSizedExtVector;
2513 void Profile(llvm::FoldingSetNodeID &ID) {
2514 Profile(ID, Context, getElementType(), getSizeExpr());
2517 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2518 QualType ElementType, Expr *SizeExpr);
2522 /// VectorType - GCC generic vector type. This type is created using
2523 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2524 /// bytes; or from an Altivec __vector or vector declaration.
2525 /// Since the constructor takes the number of vector elements, the
2526 /// client is responsible for converting the size into the number of elements.
2527 class VectorType : public Type, public llvm::FoldingSetNode {
2530 GenericVector, // not a target-specific vector type
2531 AltiVecVector, // is AltiVec vector
2532 AltiVecPixel, // is AltiVec 'vector Pixel'
2533 AltiVecBool, // is AltiVec 'vector bool ...'
2534 NeonVector, // is ARM Neon vector
2535 NeonPolyVector // is ARM Neon polynomial vector
2538 /// ElementType - The element type of the vector.
2539 QualType ElementType;
2541 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2542 VectorKind vecKind);
2544 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2545 QualType canonType, VectorKind vecKind);
2547 friend class ASTContext; // ASTContext creates these.
2551 QualType getElementType() const { return ElementType; }
2552 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2553 static bool isVectorSizeTooLarge(unsigned NumElements) {
2554 return NumElements > VectorTypeBitfields::MaxNumElements;
2557 bool isSugared() const { return false; }
2558 QualType desugar() const { return QualType(this, 0); }
2560 VectorKind getVectorKind() const {
2561 return VectorKind(VectorTypeBits.VecKind);
2564 void Profile(llvm::FoldingSetNodeID &ID) {
2565 Profile(ID, getElementType(), getNumElements(),
2566 getTypeClass(), getVectorKind());
2568 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2569 unsigned NumElements, TypeClass TypeClass,
2570 VectorKind VecKind) {
2571 ID.AddPointer(ElementType.getAsOpaquePtr());
2572 ID.AddInteger(NumElements);
2573 ID.AddInteger(TypeClass);
2574 ID.AddInteger(VecKind);
2577 static bool classof(const Type *T) {
2578 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2582 /// ExtVectorType - Extended vector type. This type is created using
2583 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2584 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2585 /// class enables syntactic extensions, like Vector Components for accessing
2586 /// points, colors, and textures (modeled after OpenGL Shading Language).
2587 class ExtVectorType : public VectorType {
2588 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2589 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2590 friend class ASTContext; // ASTContext creates these.
2592 static int getPointAccessorIdx(char c) {
2601 static int getNumericAccessorIdx(char c) {
2615 case 'a': return 10;
2617 case 'b': return 11;
2619 case 'c': return 12;
2621 case 'd': return 13;
2623 case 'e': return 14;
2625 case 'f': return 15;
2629 static int getAccessorIdx(char c) {
2630 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2631 return getNumericAccessorIdx(c);
2634 bool isAccessorWithinNumElements(char c) const {
2635 if (int idx = getAccessorIdx(c)+1)
2636 return unsigned(idx-1) < getNumElements();
2639 bool isSugared() const { return false; }
2640 QualType desugar() const { return QualType(this, 0); }
2642 static bool classof(const Type *T) {
2643 return T->getTypeClass() == ExtVector;
2647 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2648 /// class of FunctionNoProtoType and FunctionProtoType.
2650 class FunctionType : public Type {
2651 // The type returned by the function.
2652 QualType ResultType;
2655 /// ExtInfo - A class which abstracts out some details necessary for
2658 /// It is not actually used directly for storing this information in
2659 /// a FunctionType, although FunctionType does currently use the
2660 /// same bit-pattern.
2662 // If you add a field (say Foo), other than the obvious places (both,
2663 // constructors, compile failures), what you need to update is
2667 // * functionType. Add Foo, getFoo.
2668 // * ASTContext::getFooType
2669 // * ASTContext::mergeFunctionTypes
2670 // * FunctionNoProtoType::Profile
2671 // * FunctionProtoType::Profile
2672 // * TypePrinter::PrintFunctionProto
2673 // * AST read and write
2676 // Feel free to rearrange or add bits, but if you go over 9,
2677 // you'll need to adjust both the Bits field below and
2678 // Type::FunctionTypeBitfields.
2680 // | CC |noreturn|produces|regparm|
2681 // |0 .. 3| 4 | 5 | 6 .. 8|
2683 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2684 enum { CallConvMask = 0xF };
2685 enum { NoReturnMask = 0x10 };
2686 enum { ProducesResultMask = 0x20 };
2687 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2688 RegParmOffset = 6 }; // Assumed to be the last field
2692 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2694 friend class FunctionType;
2697 // Constructor with no defaults. Use this when you know that you
2698 // have all the elements (when reading an AST file for example).
2699 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2700 bool producesResult) {
2701 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2702 Bits = ((unsigned) cc) |
2703 (noReturn ? NoReturnMask : 0) |
2704 (producesResult ? ProducesResultMask : 0) |
2705 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2708 // Constructor with all defaults. Use when for example creating a
2709 // function know to use defaults.
2710 ExtInfo() : Bits(CC_C) { }
2712 // Constructor with just the calling convention, which is an important part
2713 // of the canonical type.
2714 ExtInfo(CallingConv CC) : Bits(CC) { }
2716 bool getNoReturn() const { return Bits & NoReturnMask; }
2717 bool getProducesResult() const { return Bits & ProducesResultMask; }
2718 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2719 unsigned getRegParm() const {
2720 unsigned RegParm = Bits >> RegParmOffset;
2725 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2727 bool operator==(ExtInfo Other) const {
2728 return Bits == Other.Bits;
2730 bool operator!=(ExtInfo Other) const {
2731 return Bits != Other.Bits;
2734 // Note that we don't have setters. That is by design, use
2735 // the following with methods instead of mutating these objects.
2737 ExtInfo withNoReturn(bool noReturn) const {
2739 return ExtInfo(Bits | NoReturnMask);
2741 return ExtInfo(Bits & ~NoReturnMask);
2744 ExtInfo withProducesResult(bool producesResult) const {
2746 return ExtInfo(Bits | ProducesResultMask);
2748 return ExtInfo(Bits & ~ProducesResultMask);
2751 ExtInfo withRegParm(unsigned RegParm) const {
2752 assert(RegParm < 7 && "Invalid regparm value");
2753 return ExtInfo((Bits & ~RegParmMask) |
2754 ((RegParm + 1) << RegParmOffset));
2757 ExtInfo withCallingConv(CallingConv cc) const {
2758 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2761 void Profile(llvm::FoldingSetNodeID &ID) const {
2762 ID.AddInteger(Bits);
2767 FunctionType(TypeClass tc, QualType res,
2768 unsigned typeQuals, QualType Canonical, bool Dependent,
2769 bool InstantiationDependent,
2770 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2772 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2773 ContainsUnexpandedParameterPack),
2775 FunctionTypeBits.ExtInfo = Info.Bits;
2776 FunctionTypeBits.TypeQuals = typeQuals;
2778 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2781 QualType getReturnType() const { return ResultType; }
2783 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2784 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2785 /// \brief Determine whether this function type includes the GNU noreturn
2786 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2788 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2789 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2790 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2791 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2792 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2793 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2795 /// \brief Determine the type of an expression that calls a function of
2797 QualType getCallResultType(ASTContext &Context) const {
2798 return getReturnType().getNonLValueExprType(Context);
2801 static StringRef getNameForCallConv(CallingConv CC);
2803 static bool classof(const Type *T) {
2804 return T->getTypeClass() == FunctionNoProto ||
2805 T->getTypeClass() == FunctionProto;
2809 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2810 /// no information available about its arguments.
2811 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2812 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2813 : FunctionType(FunctionNoProto, Result, 0, Canonical,
2814 /*Dependent=*/false, /*InstantiationDependent=*/false,
2815 Result->isVariablyModifiedType(),
2816 /*ContainsUnexpandedParameterPack=*/false, Info) {}
2818 friend class ASTContext; // ASTContext creates these.
2821 // No additional state past what FunctionType provides.
2823 bool isSugared() const { return false; }
2824 QualType desugar() const { return QualType(this, 0); }
2826 void Profile(llvm::FoldingSetNodeID &ID) {
2827 Profile(ID, getReturnType(), getExtInfo());
2829 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2832 ID.AddPointer(ResultType.getAsOpaquePtr());
2835 static bool classof(const Type *T) {
2836 return T->getTypeClass() == FunctionNoProto;
2840 /// FunctionProtoType - Represents a prototype with parameter type info, e.g.
2841 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
2842 /// parameters, not as having a single void parameter. Such a type can have an
2843 /// exception specification, but this specification is not part of the canonical
2845 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2847 /// ExtProtoInfo - Extra information about a function prototype.
2848 struct ExtProtoInfo {
2850 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2851 ExceptionSpecType(EST_None), RefQualifier(RQ_None), NumExceptions(0),
2852 Exceptions(nullptr), NoexceptExpr(nullptr),
2853 ExceptionSpecDecl(nullptr), ExceptionSpecTemplate(nullptr),
2854 ConsumedParameters(nullptr) {}
2856 ExtProtoInfo(CallingConv CC)
2857 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2858 ExceptionSpecType(EST_None), RefQualifier(RQ_None), NumExceptions(0),
2859 Exceptions(nullptr), NoexceptExpr(nullptr),
2860 ExceptionSpecDecl(nullptr), ExceptionSpecTemplate(nullptr),
2861 ConsumedParameters(nullptr) {}
2863 FunctionType::ExtInfo ExtInfo;
2865 bool HasTrailingReturn : 1;
2866 unsigned char TypeQuals;
2867 ExceptionSpecificationType ExceptionSpecType;
2868 RefQualifierKind RefQualifier;
2869 unsigned NumExceptions;
2870 const QualType *Exceptions;
2872 FunctionDecl *ExceptionSpecDecl;
2873 FunctionDecl *ExceptionSpecTemplate;
2874 const bool *ConsumedParameters;
2878 /// \brief Determine whether there are any argument types that
2879 /// contain an unexpanded parameter pack.
2880 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2882 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2883 if (ArgArray[Idx]->containsUnexpandedParameterPack())
2889 FunctionProtoType(QualType result, ArrayRef<QualType> params,
2890 QualType canonical, const ExtProtoInfo &epi);
2892 /// The number of parameters this function has, not counting '...'.
2893 unsigned NumParams : 15;
2895 /// NumExceptions - The number of types in the exception spec, if any.
2896 unsigned NumExceptions : 9;
2898 /// ExceptionSpecType - The type of exception specification this function has.
2899 unsigned ExceptionSpecType : 3;
2901 /// HasAnyConsumedParams - Whether this function has any consumed parameters.
2902 unsigned HasAnyConsumedParams : 1;
2904 /// Variadic - Whether the function is variadic.
2905 unsigned Variadic : 1;
2907 /// HasTrailingReturn - Whether this function has a trailing return type.
2908 unsigned HasTrailingReturn : 1;
2910 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
2912 /// This is a value of type \c RefQualifierKind.
2913 unsigned RefQualifier : 2;
2915 // ParamInfo - There is an variable size array after the class in memory that
2916 // holds the parameter types.
2918 // Exceptions - There is another variable size array after ArgInfo that
2919 // holds the exception types.
2921 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2922 // to the expression in the noexcept() specifier.
2924 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
2925 // be a pair of FunctionDecl* pointing to the function which should be used to
2926 // instantiate this function type's exception specification, and the function
2927 // from which it should be instantiated.
2929 // ConsumedParameters - A variable size array, following Exceptions
2930 // and of length NumParams, holding flags indicating which parameters
2931 // are consumed. This only appears if HasAnyConsumedParams is true.
2933 friend class ASTContext; // ASTContext creates these.
2935 const bool *getConsumedParamsBuffer() const {
2936 assert(hasAnyConsumedParams());
2938 // Find the end of the exceptions.
2939 Expr *const *eh_end = reinterpret_cast<Expr *const *>(param_type_end());
2940 if (getExceptionSpecType() != EST_ComputedNoexcept)
2941 eh_end += NumExceptions;
2943 eh_end += 1; // NoexceptExpr
2945 return reinterpret_cast<const bool*>(eh_end);
2949 unsigned getNumParams() const { return NumParams; }
2950 QualType getParamType(unsigned i) const {
2951 assert(i < NumParams && "invalid parameter index");
2952 return param_type_begin()[i];
2954 ArrayRef<QualType> getParamTypes() const {
2955 return ArrayRef<QualType>(param_type_begin(), param_type_end());
2958 ExtProtoInfo getExtProtoInfo() const {
2960 EPI.ExtInfo = getExtInfo();
2961 EPI.Variadic = isVariadic();
2962 EPI.HasTrailingReturn = hasTrailingReturn();
2963 EPI.ExceptionSpecType = getExceptionSpecType();
2964 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2965 EPI.RefQualifier = getRefQualifier();
2966 if (EPI.ExceptionSpecType == EST_Dynamic) {
2967 EPI.NumExceptions = NumExceptions;
2968 EPI.Exceptions = exception_begin();
2969 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2970 EPI.NoexceptExpr = getNoexceptExpr();
2971 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2972 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2973 EPI.ExceptionSpecTemplate = getExceptionSpecTemplate();
2974 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2975 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2977 if (hasAnyConsumedParams())
2978 EPI.ConsumedParameters = getConsumedParamsBuffer();
2982 /// \brief Get the kind of exception specification on this function.
2983 ExceptionSpecificationType getExceptionSpecType() const {
2984 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2986 /// \brief Return whether this function has any kind of exception spec.
2987 bool hasExceptionSpec() const {
2988 return getExceptionSpecType() != EST_None;
2990 /// \brief Return whether this function has a dynamic (throw) exception spec.
2991 bool hasDynamicExceptionSpec() const {
2992 return isDynamicExceptionSpec(getExceptionSpecType());
2994 /// \brief Return whether this function has a noexcept exception spec.
2995 bool hasNoexceptExceptionSpec() const {
2996 return isNoexceptExceptionSpec(getExceptionSpecType());
2998 /// \brief Result type of getNoexceptSpec().
2999 enum NoexceptResult {
3000 NR_NoNoexcept, ///< There is no noexcept specifier.
3001 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3002 NR_Dependent, ///< The noexcept specifier is dependent.
3003 NR_Throw, ///< The noexcept specifier evaluates to false.
3004 NR_Nothrow ///< The noexcept specifier evaluates to true.
3006 /// \brief Get the meaning of the noexcept spec on this function, if any.
3007 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3008 unsigned getNumExceptions() const { return NumExceptions; }
3009 QualType getExceptionType(unsigned i) const {
3010 assert(i < NumExceptions && "Invalid exception number!");
3011 return exception_begin()[i];
3013 Expr *getNoexceptExpr() const {
3014 if (getExceptionSpecType() != EST_ComputedNoexcept)
3016 // NoexceptExpr sits where the arguments end.
3017 return *reinterpret_cast<Expr *const *>(param_type_end());
3019 /// \brief If this function type has an exception specification which hasn't
3020 /// been determined yet (either because it has not been evaluated or because
3021 /// it has not been instantiated), this is the function whose exception
3022 /// specification is represented by this type.
3023 FunctionDecl *getExceptionSpecDecl() const {
3024 if (getExceptionSpecType() != EST_Uninstantiated &&
3025 getExceptionSpecType() != EST_Unevaluated)
3027 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3029 /// \brief If this function type has an uninstantiated exception
3030 /// specification, this is the function whose exception specification
3031 /// should be instantiated to find the exception specification for
3033 FunctionDecl *getExceptionSpecTemplate() const {
3034 if (getExceptionSpecType() != EST_Uninstantiated)
3036 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3038 /// \brief Determine whether this function type has a non-throwing exception
3039 /// specification. If this depends on template arguments, returns
3040 /// \c ResultIfDependent.
3041 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const;
3043 bool isVariadic() const { return Variadic; }
3045 /// \brief Determines whether this function prototype contains a
3046 /// parameter pack at the end.
3048 /// A function template whose last parameter is a parameter pack can be
3049 /// called with an arbitrary number of arguments, much like a variadic
3051 bool isTemplateVariadic() const;
3053 bool hasTrailingReturn() const { return HasTrailingReturn; }
3055 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3058 /// \brief Retrieve the ref-qualifier associated with this function type.
3059 RefQualifierKind getRefQualifier() const {
3060 return static_cast<RefQualifierKind>(RefQualifier);
3063 typedef const QualType *param_type_iterator;
3064 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3066 param_type_range param_types() const {
3067 return param_type_range(param_type_begin(), param_type_end());
3069 param_type_iterator param_type_begin() const {
3070 return reinterpret_cast<const QualType *>(this+1);
3072 param_type_iterator param_type_end() const {
3073 return param_type_begin() + NumParams;
3076 typedef const QualType *exception_iterator;
3077 typedef llvm::iterator_range<exception_iterator> exception_range;
3079 exception_range exceptions() const {
3080 return exception_range(exception_begin(), exception_end());
3082 exception_iterator exception_begin() const {
3083 // exceptions begin where arguments end
3084 return param_type_end();
3086 exception_iterator exception_end() const {
3087 if (getExceptionSpecType() != EST_Dynamic)
3088 return exception_begin();
3089 return exception_begin() + NumExceptions;
3092 bool hasAnyConsumedParams() const { return HasAnyConsumedParams; }
3093 bool isParamConsumed(unsigned I) const {
3094 assert(I < getNumParams() && "parameter index out of range");
3095 if (hasAnyConsumedParams())
3096 return getConsumedParamsBuffer()[I];
3100 bool isSugared() const { return false; }
3101 QualType desugar() const { return QualType(this, 0); }
3103 void printExceptionSpecification(raw_ostream &OS,
3104 const PrintingPolicy &Policy) const;
3106 static bool classof(const Type *T) {
3107 return T->getTypeClass() == FunctionProto;
3110 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3111 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3112 param_type_iterator ArgTys, unsigned NumArgs,
3113 const ExtProtoInfo &EPI, const ASTContext &Context);
3117 /// \brief Represents the dependent type named by a dependently-scoped
3118 /// typename using declaration, e.g.
3119 /// using typename Base<T>::foo;
3120 /// Template instantiation turns these into the underlying type.
3121 class UnresolvedUsingType : public Type {
3122 UnresolvedUsingTypenameDecl *Decl;
3124 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3125 : Type(UnresolvedUsing, QualType(), true, true, false,
3126 /*ContainsUnexpandedParameterPack=*/false),
3127 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3128 friend class ASTContext; // ASTContext creates these.
3131 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3133 bool isSugared() const { return false; }
3134 QualType desugar() const { return QualType(this, 0); }
3136 static bool classof(const Type *T) {
3137 return T->getTypeClass() == UnresolvedUsing;
3140 void Profile(llvm::FoldingSetNodeID &ID) {
3141 return Profile(ID, Decl);
3143 static void Profile(llvm::FoldingSetNodeID &ID,
3144 UnresolvedUsingTypenameDecl *D) {
3150 class TypedefType : public Type {
3151 TypedefNameDecl *Decl;
3153 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3154 : Type(tc, can, can->isDependentType(),
3155 can->isInstantiationDependentType(),
3156 can->isVariablyModifiedType(),
3157 /*ContainsUnexpandedParameterPack=*/false),
3158 Decl(const_cast<TypedefNameDecl*>(D)) {
3159 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3161 friend class ASTContext; // ASTContext creates these.
3164 TypedefNameDecl *getDecl() const { return Decl; }
3166 bool isSugared() const { return true; }
3167 QualType desugar() const;
3169 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3172 /// TypeOfExprType (GCC extension).
3173 class TypeOfExprType : public Type {
3177 TypeOfExprType(Expr *E, QualType can = QualType());
3178 friend class ASTContext; // ASTContext creates these.
3180 Expr *getUnderlyingExpr() const { return TOExpr; }
3182 /// \brief Remove a single level of sugar.
3183 QualType desugar() const;
3185 /// \brief Returns whether this type directly provides sugar.
3186 bool isSugared() const;
3188 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3191 /// \brief Internal representation of canonical, dependent
3192 /// typeof(expr) types.
3194 /// This class is used internally by the ASTContext to manage
3195 /// canonical, dependent types, only. Clients will only see instances
3196 /// of this class via TypeOfExprType nodes.
3197 class DependentTypeOfExprType
3198 : public TypeOfExprType, public llvm::FoldingSetNode {
3199 const ASTContext &Context;
3202 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3203 : TypeOfExprType(E), Context(Context) { }
3205 void Profile(llvm::FoldingSetNodeID &ID) {
3206 Profile(ID, Context, getUnderlyingExpr());
3209 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3213 /// TypeOfType (GCC extension).
3214 class TypeOfType : public Type {
3216 TypeOfType(QualType T, QualType can)
3217 : Type(TypeOf, can, T->isDependentType(),
3218 T->isInstantiationDependentType(),
3219 T->isVariablyModifiedType(),
3220 T->containsUnexpandedParameterPack()),
3222 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3224 friend class ASTContext; // ASTContext creates these.
3226 QualType getUnderlyingType() const { return TOType; }
3228 /// \brief Remove a single level of sugar.
3229 QualType desugar() const { return getUnderlyingType(); }
3231 /// \brief Returns whether this type directly provides sugar.
3232 bool isSugared() const { return true; }
3234 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3237 /// DecltypeType (C++0x)
3238 class DecltypeType : public Type {
3240 QualType UnderlyingType;
3243 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3244 friend class ASTContext; // ASTContext creates these.
3246 Expr *getUnderlyingExpr() const { return E; }
3247 QualType getUnderlyingType() const { return UnderlyingType; }
3249 /// \brief Remove a single level of sugar.
3250 QualType desugar() const;
3252 /// \brief Returns whether this type directly provides sugar.
3253 bool isSugared() const;
3255 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3258 /// \brief Internal representation of canonical, dependent
3259 /// decltype(expr) types.
3261 /// This class is used internally by the ASTContext to manage
3262 /// canonical, dependent types, only. Clients will only see instances
3263 /// of this class via DecltypeType nodes.
3264 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3265 const ASTContext &Context;
3268 DependentDecltypeType(const ASTContext &Context, Expr *E);
3270 void Profile(llvm::FoldingSetNodeID &ID) {
3271 Profile(ID, Context, getUnderlyingExpr());
3274 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3278 /// \brief A unary type transform, which is a type constructed from another
3279 class UnaryTransformType : public Type {
3286 /// The untransformed type.
3288 /// The transformed type if not dependent, otherwise the same as BaseType.
3289 QualType UnderlyingType;
3293 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3294 QualType CanonicalTy);
3295 friend class ASTContext;
3297 bool isSugared() const { return !isDependentType(); }
3298 QualType desugar() const { return UnderlyingType; }
3300 QualType getUnderlyingType() const { return UnderlyingType; }
3301 QualType getBaseType() const { return BaseType; }
3303 UTTKind getUTTKind() const { return UKind; }
3305 static bool classof(const Type *T) {
3306 return T->getTypeClass() == UnaryTransform;
3310 class TagType : public Type {
3311 /// Stores the TagDecl associated with this type. The decl may point to any
3312 /// TagDecl that declares the entity.
3315 friend class ASTReader;
3318 TagType(TypeClass TC, const TagDecl *D, QualType can);
3321 TagDecl *getDecl() const;
3323 /// @brief Determines whether this type is in the process of being
3325 bool isBeingDefined() const;
3327 static bool classof(const Type *T) {
3328 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3332 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3333 /// to detect TagType objects of structs/unions/classes.
3334 class RecordType : public TagType {
3336 explicit RecordType(const RecordDecl *D)
3337 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3338 explicit RecordType(TypeClass TC, RecordDecl *D)
3339 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3340 friend class ASTContext; // ASTContext creates these.
3343 RecordDecl *getDecl() const {
3344 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3347 // FIXME: This predicate is a helper to QualType/Type. It needs to
3348 // recursively check all fields for const-ness. If any field is declared
3349 // const, it needs to return false.
3350 bool hasConstFields() const { return false; }
3352 bool isSugared() const { return false; }
3353 QualType desugar() const { return QualType(this, 0); }
3355 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3358 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3359 /// to detect TagType objects of enums.
3360 class EnumType : public TagType {
3361 explicit EnumType(const EnumDecl *D)
3362 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3363 friend class ASTContext; // ASTContext creates these.
3366 EnumDecl *getDecl() const {
3367 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3370 bool isSugared() const { return false; }
3371 QualType desugar() const { return QualType(this, 0); }
3373 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3376 /// AttributedType - An attributed type is a type to which a type
3377 /// attribute has been applied. The "modified type" is the
3378 /// fully-sugared type to which the attributed type was applied;
3379 /// generally it is not canonically equivalent to the attributed type.
3380 /// The "equivalent type" is the minimally-desugared type which the
3381 /// type is canonically equivalent to.
3383 /// For example, in the following attributed type:
3384 /// int32_t __attribute__((vector_size(16)))
3385 /// - the modified type is the TypedefType for int32_t
3386 /// - the equivalent type is VectorType(16, int32_t)
3387 /// - the canonical type is VectorType(16, int)
3388 class AttributedType : public Type, public llvm::FoldingSetNode {
3390 // It is really silly to have yet another attribute-kind enum, but
3391 // clang::attr::Kind doesn't currently cover the pure type attrs.
3393 // Expression operand.
3397 attr_neon_vector_type,
3398 attr_neon_polyvector_type,
3400 FirstExprOperandKind = attr_address_space,
3401 LastExprOperandKind = attr_neon_polyvector_type,
3403 // Enumerated operand (string or keyword).
3405 attr_objc_ownership,
3409 FirstEnumOperandKind = attr_objc_gc,
3410 LastEnumOperandKind = attr_pcs_vfp,
3430 QualType ModifiedType;
3431 QualType EquivalentType;
3433 friend class ASTContext; // creates these
3435 AttributedType(QualType canon, Kind attrKind,
3436 QualType modified, QualType equivalent)
3437 : Type(Attributed, canon, canon->isDependentType(),
3438 canon->isInstantiationDependentType(),
3439 canon->isVariablyModifiedType(),
3440 canon->containsUnexpandedParameterPack()),
3441 ModifiedType(modified), EquivalentType(equivalent) {
3442 AttributedTypeBits.AttrKind = attrKind;
3446 Kind getAttrKind() const {
3447 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3450 QualType getModifiedType() const { return ModifiedType; }
3451 QualType getEquivalentType() const { return EquivalentType; }
3453 bool isSugared() const { return true; }
3454 QualType desugar() const { return getEquivalentType(); }
3456 bool isMSTypeSpec() const;
3458 bool isCallingConv() const;
3460 void Profile(llvm::FoldingSetNodeID &ID) {
3461 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3464 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3465 QualType modified, QualType equivalent) {
3466 ID.AddInteger(attrKind);
3467 ID.AddPointer(modified.getAsOpaquePtr());
3468 ID.AddPointer(equivalent.getAsOpaquePtr());
3471 static bool classof(const Type *T) {
3472 return T->getTypeClass() == Attributed;
3476 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3477 // Helper data collector for canonical types.
3478 struct CanonicalTTPTInfo {
3479 unsigned Depth : 15;
3480 unsigned ParameterPack : 1;
3481 unsigned Index : 16;
3485 // Info for the canonical type.
3486 CanonicalTTPTInfo CanTTPTInfo;
3487 // Info for the non-canonical type.
3488 TemplateTypeParmDecl *TTPDecl;
3491 /// Build a non-canonical type.
3492 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3493 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3494 /*InstantiationDependent=*/true,
3495 /*VariablyModified=*/false,
3496 Canon->containsUnexpandedParameterPack()),
3497 TTPDecl(TTPDecl) { }
3499 /// Build the canonical type.
3500 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3501 : Type(TemplateTypeParm, QualType(this, 0),
3503 /*InstantiationDependent=*/true,
3504 /*VariablyModified=*/false, PP) {
3505 CanTTPTInfo.Depth = D;
3506 CanTTPTInfo.Index = I;
3507 CanTTPTInfo.ParameterPack = PP;
3510 friend class ASTContext; // ASTContext creates these
3512 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3513 QualType Can = getCanonicalTypeInternal();
3514 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3518 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3519 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3520 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3522 TemplateTypeParmDecl *getDecl() const {
3523 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3526 IdentifierInfo *getIdentifier() const;
3528 bool isSugared() const { return false; }
3529 QualType desugar() const { return QualType(this, 0); }
3531 void Profile(llvm::FoldingSetNodeID &ID) {
3532 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3535 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3536 unsigned Index, bool ParameterPack,
3537 TemplateTypeParmDecl *TTPDecl) {
3538 ID.AddInteger(Depth);
3539 ID.AddInteger(Index);
3540 ID.AddBoolean(ParameterPack);
3541 ID.AddPointer(TTPDecl);
3544 static bool classof(const Type *T) {
3545 return T->getTypeClass() == TemplateTypeParm;
3549 /// \brief Represents the result of substituting a type for a template
3552 /// Within an instantiated template, all template type parameters have
3553 /// been replaced with these. They are used solely to record that a
3554 /// type was originally written as a template type parameter;
3555 /// therefore they are never canonical.
3556 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3557 // The original type parameter.
3558 const TemplateTypeParmType *Replaced;
3560 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3561 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3562 Canon->isInstantiationDependentType(),
3563 Canon->isVariablyModifiedType(),
3564 Canon->containsUnexpandedParameterPack()),
3567 friend class ASTContext;
3570 /// Gets the template parameter that was substituted for.
3571 const TemplateTypeParmType *getReplacedParameter() const {
3575 /// Gets the type that was substituted for the template
3577 QualType getReplacementType() const {
3578 return getCanonicalTypeInternal();
3581 bool isSugared() const { return true; }
3582 QualType desugar() const { return getReplacementType(); }
3584 void Profile(llvm::FoldingSetNodeID &ID) {
3585 Profile(ID, getReplacedParameter(), getReplacementType());
3587 static void Profile(llvm::FoldingSetNodeID &ID,
3588 const TemplateTypeParmType *Replaced,
3589 QualType Replacement) {
3590 ID.AddPointer(Replaced);
3591 ID.AddPointer(Replacement.getAsOpaquePtr());
3594 static bool classof(const Type *T) {
3595 return T->getTypeClass() == SubstTemplateTypeParm;
3599 /// \brief Represents the result of substituting a set of types for a template
3600 /// type parameter pack.
3602 /// When a pack expansion in the source code contains multiple parameter packs
3603 /// and those parameter packs correspond to different levels of template
3604 /// parameter lists, this type node is used to represent a template type
3605 /// parameter pack from an outer level, which has already had its argument pack
3606 /// substituted but that still lives within a pack expansion that itself
3607 /// could not be instantiated. When actually performing a substitution into
3608 /// that pack expansion (e.g., when all template parameters have corresponding
3609 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3610 /// at the current pack substitution index.
3611 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3612 /// \brief The original type parameter.
3613 const TemplateTypeParmType *Replaced;
3615 /// \brief A pointer to the set of template arguments that this
3616 /// parameter pack is instantiated with.
3617 const TemplateArgument *Arguments;
3619 /// \brief The number of template arguments in \c Arguments.
3620 unsigned NumArguments;
3622 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3624 const TemplateArgument &ArgPack);
3626 friend class ASTContext;
3629 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3631 /// Gets the template parameter that was substituted for.
3632 const TemplateTypeParmType *getReplacedParameter() const {
3636 bool isSugared() const { return false; }
3637 QualType desugar() const { return QualType(this, 0); }
3639 TemplateArgument getArgumentPack() const;
3641 void Profile(llvm::FoldingSetNodeID &ID);
3642 static void Profile(llvm::FoldingSetNodeID &ID,
3643 const TemplateTypeParmType *Replaced,
3644 const TemplateArgument &ArgPack);
3646 static bool classof(const Type *T) {
3647 return T->getTypeClass() == SubstTemplateTypeParmPack;
3651 /// \brief Represents a C++11 auto or C++1y decltype(auto) type.
3653 /// These types are usually a placeholder for a deduced type. However, before
3654 /// the initializer is attached, or if the initializer is type-dependent, there
3655 /// is no deduced type and an auto type is canonical. In the latter case, it is
3656 /// also a dependent type.
3657 class AutoType : public Type, public llvm::FoldingSetNode {
3658 AutoType(QualType DeducedType, bool IsDecltypeAuto,
3660 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3661 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3662 /*VariablyModified=*/false,
3663 /*ContainsParameterPack=*/DeducedType.isNull()
3664 ? false : DeducedType->containsUnexpandedParameterPack()) {
3665 assert((DeducedType.isNull() || !IsDependent) &&
3666 "auto deduced to dependent type");
3667 AutoTypeBits.IsDecltypeAuto = IsDecltypeAuto;
3670 friend class ASTContext; // ASTContext creates these
3673 bool isDecltypeAuto() const { return AutoTypeBits.IsDecltypeAuto; }
3675 bool isSugared() const { return !isCanonicalUnqualified(); }
3676 QualType desugar() const { return getCanonicalTypeInternal(); }
3678 /// \brief Get the type deduced for this auto type, or null if it's either
3679 /// not been deduced or was deduced to a dependent type.
3680 QualType getDeducedType() const {
3681 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3683 bool isDeduced() const {
3684 return !isCanonicalUnqualified() || isDependentType();
3687 void Profile(llvm::FoldingSetNodeID &ID) {
3688 Profile(ID, getDeducedType(), isDecltypeAuto(),
3692 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3693 bool IsDecltypeAuto, bool IsDependent) {
3694 ID.AddPointer(Deduced.getAsOpaquePtr());
3695 ID.AddBoolean(IsDecltypeAuto);
3696 ID.AddBoolean(IsDependent);
3699 static bool classof(const Type *T) {
3700 return T->getTypeClass() == Auto;
3704 /// \brief Represents a type template specialization; the template
3705 /// must be a class template, a type alias template, or a template
3706 /// template parameter. A template which cannot be resolved to one of
3707 /// these, e.g. because it is written with a dependent scope
3708 /// specifier, is instead represented as a
3709 /// @c DependentTemplateSpecializationType.
3711 /// A non-dependent template specialization type is always "sugar",
3712 /// typically for a @c RecordType. For example, a class template
3713 /// specialization type of @c vector<int> will refer to a tag type for
3714 /// the instantiation @c std::vector<int, std::allocator<int>>
3716 /// Template specializations are dependent if either the template or
3717 /// any of the template arguments are dependent, in which case the
3718 /// type may also be canonical.
3720 /// Instances of this type are allocated with a trailing array of
3721 /// TemplateArguments, followed by a QualType representing the
3722 /// non-canonical aliased type when the template is a type alias
3724 class TemplateSpecializationType
3725 : public Type, public llvm::FoldingSetNode {
3726 /// \brief The name of the template being specialized. This is
3727 /// either a TemplateName::Template (in which case it is a
3728 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3729 /// TypeAliasTemplateDecl*), a
3730 /// TemplateName::SubstTemplateTemplateParmPack, or a
3731 /// TemplateName::SubstTemplateTemplateParm (in which case the
3732 /// replacement must, recursively, be one of these).
3733 TemplateName Template;
3735 /// \brief - The number of template arguments named in this class
3736 /// template specialization.
3737 unsigned NumArgs : 31;
3739 /// \brief Whether this template specialization type is a substituted
3743 TemplateSpecializationType(TemplateName T,
3744 const TemplateArgument *Args,
3745 unsigned NumArgs, QualType Canon,
3748 friend class ASTContext; // ASTContext creates these
3751 /// \brief Determine whether any of the given template arguments are
3753 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3755 bool &InstantiationDependent);
3757 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3758 bool &InstantiationDependent);
3760 /// \brief Print a template argument list, including the '<' and '>'
3761 /// enclosing the template arguments.
3762 static void PrintTemplateArgumentList(raw_ostream &OS,
3763 const TemplateArgument *Args,
3765 const PrintingPolicy &Policy,
3766 bool SkipBrackets = false);
3768 static void PrintTemplateArgumentList(raw_ostream &OS,
3769 const TemplateArgumentLoc *Args,
3771 const PrintingPolicy &Policy);
3773 static void PrintTemplateArgumentList(raw_ostream &OS,
3774 const TemplateArgumentListInfo &,
3775 const PrintingPolicy &Policy);
3777 /// True if this template specialization type matches a current
3778 /// instantiation in the context in which it is found.
3779 bool isCurrentInstantiation() const {
3780 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3783 /// \brief Determine if this template specialization type is for a type alias
3784 /// template that has been substituted.
3786 /// Nearly every template specialization type whose template is an alias
3787 /// template will be substituted. However, this is not the case when
3788 /// the specialization contains a pack expansion but the template alias
3789 /// does not have a corresponding parameter pack, e.g.,
3792 /// template<typename T, typename U, typename V> struct S;
3793 /// template<typename T, typename U> using A = S<T, int, U>;
3794 /// template<typename... Ts> struct X {
3795 /// typedef A<Ts...> type; // not a type alias
3798 bool isTypeAlias() const { return TypeAlias; }
3800 /// Get the aliased type, if this is a specialization of a type alias
3802 QualType getAliasedType() const {
3803 assert(isTypeAlias() && "not a type alias template specialization");
3804 return *reinterpret_cast<const QualType*>(end());
3807 typedef const TemplateArgument * iterator;
3809 iterator begin() const { return getArgs(); }
3810 iterator end() const; // defined inline in TemplateBase.h
3812 /// \brief Retrieve the name of the template that we are specializing.
3813 TemplateName getTemplateName() const { return Template; }
3815 /// \brief Retrieve the template arguments.
3816 const TemplateArgument *getArgs() const {
3817 return reinterpret_cast<const TemplateArgument *>(this + 1);
3820 /// \brief Retrieve the number of template arguments.
3821 unsigned getNumArgs() const { return NumArgs; }
3823 /// \brief Retrieve a specific template argument as a type.
3824 /// \pre @c isArgType(Arg)
3825 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3827 bool isSugared() const {
3828 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3830 QualType desugar() const { return getCanonicalTypeInternal(); }
3832 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3833 Profile(ID, Template, getArgs(), NumArgs, Ctx);
3835 getAliasedType().Profile(ID);
3838 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3839 const TemplateArgument *Args,
3841 const ASTContext &Context);
3843 static bool classof(const Type *T) {
3844 return T->getTypeClass() == TemplateSpecialization;
3848 /// \brief The injected class name of a C++ class template or class
3849 /// template partial specialization. Used to record that a type was
3850 /// spelled with a bare identifier rather than as a template-id; the
3851 /// equivalent for non-templated classes is just RecordType.
3853 /// Injected class name types are always dependent. Template
3854 /// instantiation turns these into RecordTypes.
3856 /// Injected class name types are always canonical. This works
3857 /// because it is impossible to compare an injected class name type
3858 /// with the corresponding non-injected template type, for the same
3859 /// reason that it is impossible to directly compare template
3860 /// parameters from different dependent contexts: injected class name
3861 /// types can only occur within the scope of a particular templated
3862 /// declaration, and within that scope every template specialization
3863 /// will canonicalize to the injected class name (when appropriate
3864 /// according to the rules of the language).
3865 class InjectedClassNameType : public Type {
3866 CXXRecordDecl *Decl;
3868 /// The template specialization which this type represents.
3870 /// template <class T> class A { ... };
3871 /// this is A<T>, whereas in
3872 /// template <class X, class Y> class A<B<X,Y> > { ... };
3873 /// this is A<B<X,Y> >.
3875 /// It is always unqualified, always a template specialization type,
3876 /// and always dependent.
3877 QualType InjectedType;
3879 friend class ASTContext; // ASTContext creates these.
3880 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3881 // currently suitable for AST reading, too much
3882 // interdependencies.
3883 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3884 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3885 /*InstantiationDependent=*/true,
3886 /*VariablyModified=*/false,
3887 /*ContainsUnexpandedParameterPack=*/false),
3888 Decl(D), InjectedType(TST) {
3889 assert(isa<TemplateSpecializationType>(TST));
3890 assert(!TST.hasQualifiers());
3891 assert(TST->isDependentType());
3895 QualType getInjectedSpecializationType() const { return InjectedType; }
3896 const TemplateSpecializationType *getInjectedTST() const {
3897 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3900 CXXRecordDecl *getDecl() const;
3902 bool isSugared() const { return false; }
3903 QualType desugar() const { return QualType(this, 0); }
3905 static bool classof(const Type *T) {
3906 return T->getTypeClass() == InjectedClassName;
3910 /// \brief The kind of a tag type.
3912 /// \brief The "struct" keyword.
3914 /// \brief The "__interface" keyword.
3916 /// \brief The "union" keyword.
3918 /// \brief The "class" keyword.
3920 /// \brief The "enum" keyword.
3924 /// \brief The elaboration keyword that precedes a qualified type name or
3925 /// introduces an elaborated-type-specifier.
3926 enum ElaboratedTypeKeyword {
3927 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3929 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
3931 /// \brief The "union" keyword introduces the elaborated-type-specifier.
3933 /// \brief The "class" keyword introduces the elaborated-type-specifier.
3935 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3937 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3938 /// \c typename T::type.
3940 /// \brief No keyword precedes the qualified type name.
3944 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
3945 /// The keyword in stored in the free bits of the base class.
3946 /// Also provides a few static helpers for converting and printing
3947 /// elaborated type keyword and tag type kind enumerations.
3948 class TypeWithKeyword : public Type {
3950 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3951 QualType Canonical, bool Dependent,
3952 bool InstantiationDependent, bool VariablyModified,
3953 bool ContainsUnexpandedParameterPack)
3954 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3955 ContainsUnexpandedParameterPack) {
3956 TypeWithKeywordBits.Keyword = Keyword;
3960 ElaboratedTypeKeyword getKeyword() const {
3961 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3964 /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3965 /// into an elaborated type keyword.
3966 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3968 /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3969 /// into a tag type kind. It is an error to provide a type specifier
3970 /// which *isn't* a tag kind here.
3971 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3973 /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3974 /// elaborated type keyword.
3975 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3977 /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3978 // a TagTypeKind. It is an error to provide an elaborated type keyword
3979 /// which *isn't* a tag kind here.
3980 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3982 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3984 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
3986 static StringRef getTagTypeKindName(TagTypeKind Kind) {
3987 return getKeywordName(getKeywordForTagTypeKind(Kind));
3990 class CannotCastToThisType {};
3991 static CannotCastToThisType classof(const Type *);
3994 /// \brief Represents a type that was referred to using an elaborated type
3995 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3998 /// This type is used to keep track of a type name as written in the
3999 /// source code, including tag keywords and any nested-name-specifiers.
4000 /// The type itself is always "sugar", used to express what was written
4001 /// in the source code but containing no additional semantic information.
4002 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4004 /// \brief The nested name specifier containing the qualifier.
4005 NestedNameSpecifier *NNS;
4007 /// \brief The type that this qualified name refers to.
4010 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4011 QualType NamedType, QualType CanonType)
4012 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4013 NamedType->isDependentType(),
4014 NamedType->isInstantiationDependentType(),
4015 NamedType->isVariablyModifiedType(),
4016 NamedType->containsUnexpandedParameterPack()),
4017 NNS(NNS), NamedType(NamedType) {
4018 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4019 "ElaboratedType cannot have elaborated type keyword "
4020 "and name qualifier both null.");
4023 friend class ASTContext; // ASTContext creates these
4028 /// \brief Retrieve the qualification on this type.
4029 NestedNameSpecifier *getQualifier() const { return NNS; }
4031 /// \brief Retrieve the type named by the qualified-id.
4032 QualType getNamedType() const { return NamedType; }
4034 /// \brief Remove a single level of sugar.
4035 QualType desugar() const { return getNamedType(); }
4037 /// \brief Returns whether this type directly provides sugar.
4038 bool isSugared() const { return true; }
4040 void Profile(llvm::FoldingSetNodeID &ID) {
4041 Profile(ID, getKeyword(), NNS, NamedType);
4044 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4045 NestedNameSpecifier *NNS, QualType NamedType) {
4046 ID.AddInteger(Keyword);
4048 NamedType.Profile(ID);
4051 static bool classof(const Type *T) {
4052 return T->getTypeClass() == Elaborated;
4056 /// \brief Represents a qualified type name for which the type name is
4059 /// DependentNameType represents a class of dependent types that involve a
4060 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4061 /// name of a type. The DependentNameType may start with a "typename" (for a
4062 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4063 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4064 /// know that we must be referring to a type, e.g., in a base class specifier).
4065 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4066 /// mode, this type is used with non-dependent names to delay name lookup until
4068 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4070 /// \brief The nested name specifier containing the qualifier.
4071 NestedNameSpecifier *NNS;
4073 /// \brief The type that this typename specifier refers to.
4074 const IdentifierInfo *Name;
4076 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4077 const IdentifierInfo *Name, QualType CanonType)
4078 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4079 /*InstantiationDependent=*/true,
4080 /*VariablyModified=*/false,
4081 NNS->containsUnexpandedParameterPack()),
4082 NNS(NNS), Name(Name) {}
4084 friend class ASTContext; // ASTContext creates these
4087 /// \brief Retrieve the qualification on this type.
4088 NestedNameSpecifier *getQualifier() const { return NNS; }
4090 /// \brief Retrieve the type named by the typename specifier as an
4093 /// This routine will return a non-NULL identifier pointer when the
4094 /// form of the original typename was terminated by an identifier,
4095 /// e.g., "typename T::type".
4096 const IdentifierInfo *getIdentifier() const {
4100 bool isSugared() const { return false; }
4101 QualType desugar() const { return QualType(this, 0); }
4103 void Profile(llvm::FoldingSetNodeID &ID) {
4104 Profile(ID, getKeyword(), NNS, Name);
4107 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4108 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4109 ID.AddInteger(Keyword);
4111 ID.AddPointer(Name);
4114 static bool classof(const Type *T) {
4115 return T->getTypeClass() == DependentName;
4119 /// DependentTemplateSpecializationType - Represents a template
4120 /// specialization type whose template cannot be resolved, e.g.
4121 /// A<T>::template B<T>
4122 class DependentTemplateSpecializationType :
4123 public TypeWithKeyword, public llvm::FoldingSetNode {
4125 /// \brief The nested name specifier containing the qualifier.
4126 NestedNameSpecifier *NNS;
4128 /// \brief The identifier of the template.
4129 const IdentifierInfo *Name;
4131 /// \brief - The number of template arguments named in this class
4132 /// template specialization.
4135 const TemplateArgument *getArgBuffer() const {
4136 return reinterpret_cast<const TemplateArgument*>(this+1);
4138 TemplateArgument *getArgBuffer() {
4139 return reinterpret_cast<TemplateArgument*>(this+1);
4142 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4143 NestedNameSpecifier *NNS,
4144 const IdentifierInfo *Name,
4146 const TemplateArgument *Args,
4149 friend class ASTContext; // ASTContext creates these
4152 NestedNameSpecifier *getQualifier() const { return NNS; }
4153 const IdentifierInfo *getIdentifier() const { return Name; }
4155 /// \brief Retrieve the template arguments.
4156 const TemplateArgument *getArgs() const {
4157 return getArgBuffer();
4160 /// \brief Retrieve the number of template arguments.
4161 unsigned getNumArgs() const { return NumArgs; }
4163 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4165 typedef const TemplateArgument * iterator;
4166 iterator begin() const { return getArgs(); }
4167 iterator end() const; // inline in TemplateBase.h
4169 bool isSugared() const { return false; }
4170 QualType desugar() const { return QualType(this, 0); }
4172 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4173 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4176 static void Profile(llvm::FoldingSetNodeID &ID,
4177 const ASTContext &Context,
4178 ElaboratedTypeKeyword Keyword,
4179 NestedNameSpecifier *Qualifier,
4180 const IdentifierInfo *Name,
4182 const TemplateArgument *Args);
4184 static bool classof(const Type *T) {
4185 return T->getTypeClass() == DependentTemplateSpecialization;
4189 /// \brief Represents a pack expansion of types.
4191 /// Pack expansions are part of C++0x variadic templates. A pack
4192 /// expansion contains a pattern, which itself contains one or more
4193 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4194 /// produces a series of types, each instantiated from the pattern of
4195 /// the expansion, where the Ith instantiation of the pattern uses the
4196 /// Ith arguments bound to each of the unexpanded parameter packs. The
4197 /// pack expansion is considered to "expand" these unexpanded
4198 /// parameter packs.
4201 /// template<typename ...Types> struct tuple;
4203 /// template<typename ...Types>
4204 /// struct tuple_of_references {
4205 /// typedef tuple<Types&...> type;
4209 /// Here, the pack expansion \c Types&... is represented via a
4210 /// PackExpansionType whose pattern is Types&.
4211 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4212 /// \brief The pattern of the pack expansion.
4215 /// \brief The number of expansions that this pack expansion will
4216 /// generate when substituted (+1), or indicates that
4218 /// This field will only have a non-zero value when some of the parameter
4219 /// packs that occur within the pattern have been substituted but others have
4221 unsigned NumExpansions;
4223 PackExpansionType(QualType Pattern, QualType Canon,
4224 Optional<unsigned> NumExpansions)
4225 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4226 /*InstantiationDependent=*/true,
4227 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4228 /*ContainsUnexpandedParameterPack=*/false),
4230 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4232 friend class ASTContext; // ASTContext creates these
4235 /// \brief Retrieve the pattern of this pack expansion, which is the
4236 /// type that will be repeatedly instantiated when instantiating the
4237 /// pack expansion itself.
4238 QualType getPattern() const { return Pattern; }
4240 /// \brief Retrieve the number of expansions that this pack expansion will
4241 /// generate, if known.
4242 Optional<unsigned> getNumExpansions() const {
4244 return NumExpansions - 1;
4249 bool isSugared() const { return !Pattern->isDependentType(); }
4250 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4252 void Profile(llvm::FoldingSetNodeID &ID) {
4253 Profile(ID, getPattern(), getNumExpansions());
4256 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4257 Optional<unsigned> NumExpansions) {
4258 ID.AddPointer(Pattern.getAsOpaquePtr());
4259 ID.AddBoolean(NumExpansions.hasValue());
4261 ID.AddInteger(*NumExpansions);
4264 static bool classof(const Type *T) {
4265 return T->getTypeClass() == PackExpansion;
4269 /// ObjCObjectType - Represents a class type in Objective C.
4270 /// Every Objective C type is a combination of a base type and a
4271 /// list of protocols.
4273 /// Given the following declarations:
4279 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4280 /// with base C and no protocols.
4282 /// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4284 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4285 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4286 /// and no protocols.
4288 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4289 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4290 /// this should get its own sugar class to better represent the source.
4291 class ObjCObjectType : public Type {
4292 // ObjCObjectType.NumProtocols - the number of protocols stored
4293 // after the ObjCObjectPointerType node.
4295 // These protocols are those written directly on the type. If
4296 // protocol qualifiers ever become additive, the iterators will need
4297 // to get kindof complicated.
4299 // In the canonical object type, these are sorted alphabetically
4302 /// Either a BuiltinType or an InterfaceType or sugar for either.
4305 ObjCProtocolDecl * const *getProtocolStorage() const {
4306 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4309 ObjCProtocolDecl **getProtocolStorage();
4312 ObjCObjectType(QualType Canonical, QualType Base,
4313 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4315 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4316 ObjCObjectType(enum Nonce_ObjCInterface)
4317 : Type(ObjCInterface, QualType(), false, false, false, false),
4318 BaseType(QualType(this_(), 0)) {
4319 ObjCObjectTypeBits.NumProtocols = 0;
4323 /// getBaseType - Gets the base type of this object type. This is
4324 /// always (possibly sugar for) one of:
4325 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4326 /// user, which is a typedef for an ObjCObjectPointerType)
4327 /// - the 'Class' builtin type (same caveat)
4328 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4329 QualType getBaseType() const { return BaseType; }
4331 bool isObjCId() const {
4332 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4334 bool isObjCClass() const {
4335 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4337 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4338 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4339 bool isObjCUnqualifiedIdOrClass() const {
4340 if (!qual_empty()) return false;
4341 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4342 return T->getKind() == BuiltinType::ObjCId ||
4343 T->getKind() == BuiltinType::ObjCClass;
4346 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4347 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4349 /// Gets the interface declaration for this object type, if the base type
4350 /// really is an interface.
4351 ObjCInterfaceDecl *getInterface() const;
4353 typedef ObjCProtocolDecl * const *qual_iterator;
4354 typedef llvm::iterator_range<qual_iterator> qual_range;
4356 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4357 qual_iterator qual_begin() const { return getProtocolStorage(); }
4358 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4360 bool qual_empty() const { return getNumProtocols() == 0; }
4362 /// getNumProtocols - Return the number of qualifying protocols in this
4363 /// interface type, or 0 if there are none.
4364 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4366 /// \brief Fetch a protocol by index.
4367 ObjCProtocolDecl *getProtocol(unsigned I) const {
4368 assert(I < getNumProtocols() && "Out-of-range protocol access");
4369 return qual_begin()[I];
4372 bool isSugared() const { return false; }
4373 QualType desugar() const { return QualType(this, 0); }
4375 static bool classof(const Type *T) {
4376 return T->getTypeClass() == ObjCObject ||
4377 T->getTypeClass() == ObjCInterface;
4381 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4382 /// of ObjCObjectType, so as to not increase the footprint of
4383 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4384 /// system should not reference this type.
4385 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4386 friend class ASTContext;
4388 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4389 // will need to be modified.
4391 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4392 ObjCProtocolDecl * const *Protocols,
4393 unsigned NumProtocols)
4394 : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4397 void Profile(llvm::FoldingSetNodeID &ID);
4398 static void Profile(llvm::FoldingSetNodeID &ID,
4400 ObjCProtocolDecl *const *protocols,
4401 unsigned NumProtocols);
4404 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4405 return reinterpret_cast<ObjCProtocolDecl**>(
4406 static_cast<ObjCObjectTypeImpl*>(this) + 1);
4409 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4410 /// object oriented design. They basically correspond to C++ classes. There
4411 /// are two kinds of interface types, normal interfaces like "NSString" and
4412 /// qualified interfaces, which are qualified with a protocol list like
4413 /// "NSString<NSCopyable, NSAmazing>".
4415 /// ObjCInterfaceType guarantees the following properties when considered
4416 /// as a subtype of its superclass, ObjCObjectType:
4417 /// - There are no protocol qualifiers. To reinforce this, code which
4418 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4419 /// fail to compile.
4420 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4421 /// T->getBaseType() == QualType(T, 0).
4422 class ObjCInterfaceType : public ObjCObjectType {
4423 mutable ObjCInterfaceDecl *Decl;
4425 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4426 : ObjCObjectType(Nonce_ObjCInterface),
4427 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4428 friend class ASTContext; // ASTContext creates these.
4429 friend class ASTReader;
4430 friend class ObjCInterfaceDecl;
4433 /// getDecl - Get the declaration of this interface.
4434 ObjCInterfaceDecl *getDecl() const { return Decl; }
4436 bool isSugared() const { return false; }
4437 QualType desugar() const { return QualType(this, 0); }
4439 static bool classof(const Type *T) {
4440 return T->getTypeClass() == ObjCInterface;
4443 // Nonsense to "hide" certain members of ObjCObjectType within this
4444 // class. People asking for protocols on an ObjCInterfaceType are
4445 // not going to get what they want: ObjCInterfaceTypes are
4446 // guaranteed to have no protocols.
4456 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4457 if (const ObjCInterfaceType *T =
4458 getBaseType()->getAs<ObjCInterfaceType>())
4459 return T->getDecl();
4463 /// ObjCObjectPointerType - Used to represent a pointer to an
4464 /// Objective C object. These are constructed from pointer
4465 /// declarators when the pointee type is an ObjCObjectType (or sugar
4466 /// for one). In addition, the 'id' and 'Class' types are typedefs
4467 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4468 /// are translated into these.
4470 /// Pointers to pointers to Objective C objects are still PointerTypes;
4471 /// only the first level of pointer gets it own type implementation.
4472 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4473 QualType PointeeType;
4475 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4476 : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4477 PointeeType(Pointee) {}
4478 friend class ASTContext; // ASTContext creates these.
4481 /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4482 /// The result will always be an ObjCObjectType or sugar thereof.
4483 QualType getPointeeType() const { return PointeeType; }
4485 /// getObjCObjectType - Gets the type pointed to by this ObjC
4486 /// pointer. This method always returns non-null.
4488 /// This method is equivalent to getPointeeType() except that
4489 /// it discards any typedefs (or other sugar) between this
4490 /// type and the "outermost" object type. So for:
4492 /// \@class A; \@protocol P; \@protocol Q;
4493 /// typedef A<P> AP;
4495 /// typedef A1<P> A1P;
4496 /// typedef A1P<Q> A1PQ;
4498 /// For 'A*', getObjectType() will return 'A'.
4499 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4500 /// For 'AP*', getObjectType() will return 'A<P>'.
4501 /// For 'A1*', getObjectType() will return 'A'.
4502 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4503 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4504 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4505 /// adding protocols to a protocol-qualified base discards the
4506 /// old qualifiers (for now). But if it didn't, getObjectType()
4507 /// would return 'A1P<Q>' (and we'd have to make iterating over
4508 /// qualifiers more complicated).
4509 const ObjCObjectType *getObjectType() const {
4510 return PointeeType->castAs<ObjCObjectType>();
4513 /// getInterfaceType - If this pointer points to an Objective C
4514 /// \@interface type, gets the type for that interface. Any protocol
4515 /// qualifiers on the interface are ignored.
4517 /// \return null if the base type for this pointer is 'id' or 'Class'
4518 const ObjCInterfaceType *getInterfaceType() const {
4519 return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4522 /// getInterfaceDecl - If this pointer points to an Objective \@interface
4523 /// type, gets the declaration for that interface.
4525 /// \return null if the base type for this pointer is 'id' or 'Class'
4526 ObjCInterfaceDecl *getInterfaceDecl() const {
4527 return getObjectType()->getInterface();
4530 /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4531 /// its object type is the primitive 'id' type with no protocols.
4532 bool isObjCIdType() const {
4533 return getObjectType()->isObjCUnqualifiedId();
4536 /// isObjCClassType - True if this is equivalent to the 'Class' type,
4537 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4538 bool isObjCClassType() const {
4539 return getObjectType()->isObjCUnqualifiedClass();
4542 /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4543 /// non-empty set of protocols.
4544 bool isObjCQualifiedIdType() const {
4545 return getObjectType()->isObjCQualifiedId();
4548 /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4549 /// some non-empty set of protocols.
4550 bool isObjCQualifiedClassType() const {
4551 return getObjectType()->isObjCQualifiedClass();
4554 /// An iterator over the qualifiers on the object type. Provided
4555 /// for convenience. This will always iterate over the full set of
4556 /// protocols on a type, not just those provided directly.
4557 typedef ObjCObjectType::qual_iterator qual_iterator;
4558 typedef llvm::iterator_range<qual_iterator> qual_range;
4560 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4561 qual_iterator qual_begin() const {
4562 return getObjectType()->qual_begin();
4564 qual_iterator qual_end() const {
4565 return getObjectType()->qual_end();
4567 bool qual_empty() const { return getObjectType()->qual_empty(); }
4569 /// getNumProtocols - Return the number of qualifying protocols on
4570 /// the object type.
4571 unsigned getNumProtocols() const {
4572 return getObjectType()->getNumProtocols();
4575 /// \brief Retrieve a qualifying protocol by index on the object
4577 ObjCProtocolDecl *getProtocol(unsigned I) const {
4578 return getObjectType()->getProtocol(I);
4581 bool isSugared() const { return false; }
4582 QualType desugar() const { return QualType(this, 0); }
4584 void Profile(llvm::FoldingSetNodeID &ID) {
4585 Profile(ID, getPointeeType());
4587 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4588 ID.AddPointer(T.getAsOpaquePtr());
4590 static bool classof(const Type *T) {
4591 return T->getTypeClass() == ObjCObjectPointer;
4595 class AtomicType : public Type, public llvm::FoldingSetNode {
4598 AtomicType(QualType ValTy, QualType Canonical)
4599 : Type(Atomic, Canonical, ValTy->isDependentType(),
4600 ValTy->isInstantiationDependentType(),
4601 ValTy->isVariablyModifiedType(),
4602 ValTy->containsUnexpandedParameterPack()),
4604 friend class ASTContext; // ASTContext creates these.
4607 /// getValueType - Gets the type contained by this atomic type, i.e.
4608 /// the type returned by performing an atomic load of this atomic type.
4609 QualType getValueType() const { return ValueType; }
4611 bool isSugared() const { return false; }
4612 QualType desugar() const { return QualType(this, 0); }
4614 void Profile(llvm::FoldingSetNodeID &ID) {
4615 Profile(ID, getValueType());
4617 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4618 ID.AddPointer(T.getAsOpaquePtr());
4620 static bool classof(const Type *T) {
4621 return T->getTypeClass() == Atomic;
4625 /// A qualifier set is used to build a set of qualifiers.
4626 class QualifierCollector : public Qualifiers {
4628 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4630 /// Collect any qualifiers on the given type and return an
4631 /// unqualified type. The qualifiers are assumed to be consistent
4632 /// with those already in the type.
4633 const Type *strip(QualType type) {
4634 addFastQualifiers(type.getLocalFastQualifiers());
4635 if (!type.hasLocalNonFastQualifiers())
4636 return type.getTypePtrUnsafe();
4638 const ExtQuals *extQuals = type.getExtQualsUnsafe();
4639 addConsistentQualifiers(extQuals->getQualifiers());
4640 return extQuals->getBaseType();
4643 /// Apply the collected qualifiers to the given type.
4644 QualType apply(const ASTContext &Context, QualType QT) const;
4646 /// Apply the collected qualifiers to the given type.
4647 QualType apply(const ASTContext &Context, const Type* T) const;
4651 // Inline function definitions.
4653 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
4654 SplitQualType desugar =
4655 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
4656 desugar.Quals.addConsistentQualifiers(Quals);
4660 inline const Type *QualType::getTypePtr() const {
4661 return getCommonPtr()->BaseType;
4664 inline const Type *QualType::getTypePtrOrNull() const {
4665 return (isNull() ? nullptr : getCommonPtr()->BaseType);
4668 inline SplitQualType QualType::split() const {
4669 if (!hasLocalNonFastQualifiers())
4670 return SplitQualType(getTypePtrUnsafe(),
4671 Qualifiers::fromFastMask(getLocalFastQualifiers()));
4673 const ExtQuals *eq = getExtQualsUnsafe();
4674 Qualifiers qs = eq->getQualifiers();
4675 qs.addFastQualifiers(getLocalFastQualifiers());
4676 return SplitQualType(eq->getBaseType(), qs);
4679 inline Qualifiers QualType::getLocalQualifiers() const {
4681 if (hasLocalNonFastQualifiers())
4682 Quals = getExtQualsUnsafe()->getQualifiers();
4683 Quals.addFastQualifiers(getLocalFastQualifiers());
4687 inline Qualifiers QualType::getQualifiers() const {
4688 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4689 quals.addFastQualifiers(getLocalFastQualifiers());
4693 inline unsigned QualType::getCVRQualifiers() const {
4694 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4695 cvr |= getLocalCVRQualifiers();
4699 inline QualType QualType::getCanonicalType() const {
4700 QualType canon = getCommonPtr()->CanonicalType;
4701 return canon.withFastQualifiers(getLocalFastQualifiers());
4704 inline bool QualType::isCanonical() const {
4705 return getTypePtr()->isCanonicalUnqualified();
4708 inline bool QualType::isCanonicalAsParam() const {
4709 if (!isCanonical()) return false;
4710 if (hasLocalQualifiers()) return false;
4712 const Type *T = getTypePtr();
4713 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4716 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4719 inline bool QualType::isConstQualified() const {
4720 return isLocalConstQualified() ||
4721 getCommonPtr()->CanonicalType.isLocalConstQualified();
4724 inline bool QualType::isRestrictQualified() const {
4725 return isLocalRestrictQualified() ||
4726 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4730 inline bool QualType::isVolatileQualified() const {
4731 return isLocalVolatileQualified() ||
4732 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4735 inline bool QualType::hasQualifiers() const {
4736 return hasLocalQualifiers() ||
4737 getCommonPtr()->CanonicalType.hasLocalQualifiers();
4740 inline QualType QualType::getUnqualifiedType() const {
4741 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4742 return QualType(getTypePtr(), 0);
4744 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
4747 inline SplitQualType QualType::getSplitUnqualifiedType() const {
4748 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4751 return getSplitUnqualifiedTypeImpl(*this);
4754 inline void QualType::removeLocalConst() {
4755 removeLocalFastQualifiers(Qualifiers::Const);
4758 inline void QualType::removeLocalRestrict() {
4759 removeLocalFastQualifiers(Qualifiers::Restrict);
4762 inline void QualType::removeLocalVolatile() {
4763 removeLocalFastQualifiers(Qualifiers::Volatile);
4766 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4767 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4768 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4770 // Fast path: we don't need to touch the slow qualifiers.
4771 removeLocalFastQualifiers(Mask);
4774 /// getAddressSpace - Return the address space of this type.
4775 inline unsigned QualType::getAddressSpace() const {
4776 return getQualifiers().getAddressSpace();
4779 /// getObjCGCAttr - Return the gc attribute of this type.
4780 inline Qualifiers::GC QualType::getObjCGCAttr() const {
4781 return getQualifiers().getObjCGCAttr();
4784 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4785 if (const PointerType *PT = t.getAs<PointerType>()) {
4786 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4787 return FT->getExtInfo();
4788 } else if (const FunctionType *FT = t.getAs<FunctionType>())
4789 return FT->getExtInfo();
4791 return FunctionType::ExtInfo();
4794 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4795 return getFunctionExtInfo(*t);
4798 /// isMoreQualifiedThan - Determine whether this type is more
4799 /// qualified than the Other type. For example, "const volatile int"
4800 /// is more qualified than "const int", "volatile int", and
4801 /// "int". However, it is not more qualified than "const volatile
4803 inline bool QualType::isMoreQualifiedThan(QualType other) const {
4804 Qualifiers myQuals = getQualifiers();
4805 Qualifiers otherQuals = other.getQualifiers();
4806 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4809 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
4810 /// as qualified as the Other type. For example, "const volatile
4811 /// int" is at least as qualified as "const int", "volatile int",
4812 /// "int", and "const volatile int".
4813 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4814 return getQualifiers().compatiblyIncludes(other.getQualifiers());
4817 /// getNonReferenceType - If Type is a reference type (e.g., const
4818 /// int&), returns the type that the reference refers to ("const
4819 /// int"). Otherwise, returns the type itself. This routine is used
4820 /// throughout Sema to implement C++ 5p6:
4822 /// If an expression initially has the type "reference to T" (8.3.2,
4823 /// 8.5.3), the type is adjusted to "T" prior to any further
4824 /// analysis, the expression designates the object or function
4825 /// denoted by the reference, and the expression is an lvalue.
4826 inline QualType QualType::getNonReferenceType() const {
4827 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4828 return RefType->getPointeeType();
4833 inline bool QualType::isCForbiddenLValueType() const {
4834 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4835 getTypePtr()->isFunctionType());
4838 /// \brief Tests whether the type is categorized as a fundamental type.
4840 /// \returns True for types specified in C++0x [basic.fundamental].
4841 inline bool Type::isFundamentalType() const {
4842 return isVoidType() ||
4843 // FIXME: It's really annoying that we don't have an
4844 // 'isArithmeticType()' which agrees with the standard definition.
4845 (isArithmeticType() && !isEnumeralType());
4848 /// \brief Tests whether the type is categorized as a compound type.
4850 /// \returns True for types specified in C++0x [basic.compound].
4851 inline bool Type::isCompoundType() const {
4852 // C++0x [basic.compound]p1:
4853 // Compound types can be constructed in the following ways:
4854 // -- arrays of objects of a given type [...];
4855 return isArrayType() ||
4856 // -- functions, which have parameters of given types [...];
4858 // -- pointers to void or objects or functions [...];
4860 // -- references to objects or functions of a given type. [...]
4861 isReferenceType() ||
4862 // -- classes containing a sequence of objects of various types, [...];
4864 // -- unions, which are classes capable of containing objects of different
4865 // types at different times;
4867 // -- enumerations, which comprise a set of named constant values. [...];
4869 // -- pointers to non-static class members, [...].
4870 isMemberPointerType();
4873 inline bool Type::isFunctionType() const {
4874 return isa<FunctionType>(CanonicalType);
4876 inline bool Type::isPointerType() const {
4877 return isa<PointerType>(CanonicalType);
4879 inline bool Type::isAnyPointerType() const {
4880 return isPointerType() || isObjCObjectPointerType();
4882 inline bool Type::isBlockPointerType() const {
4883 return isa<BlockPointerType>(CanonicalType);
4885 inline bool Type::isReferenceType() const {
4886 return isa<ReferenceType>(CanonicalType);
4888 inline bool Type::isLValueReferenceType() const {
4889 return isa<LValueReferenceType>(CanonicalType);
4891 inline bool Type::isRValueReferenceType() const {
4892 return isa<RValueReferenceType>(CanonicalType);
4894 inline bool Type::isFunctionPointerType() const {
4895 if (const PointerType *T = getAs<PointerType>())
4896 return T->getPointeeType()->isFunctionType();
4900 inline bool Type::isMemberPointerType() const {
4901 return isa<MemberPointerType>(CanonicalType);
4903 inline bool Type::isMemberFunctionPointerType() const {
4904 if (const MemberPointerType* T = getAs<MemberPointerType>())
4905 return T->isMemberFunctionPointer();
4909 inline bool Type::isMemberDataPointerType() const {
4910 if (const MemberPointerType* T = getAs<MemberPointerType>())
4911 return T->isMemberDataPointer();
4915 inline bool Type::isArrayType() const {
4916 return isa<ArrayType>(CanonicalType);
4918 inline bool Type::isConstantArrayType() const {
4919 return isa<ConstantArrayType>(CanonicalType);
4921 inline bool Type::isIncompleteArrayType() const {
4922 return isa<IncompleteArrayType>(CanonicalType);
4924 inline bool Type::isVariableArrayType() const {
4925 return isa<VariableArrayType>(CanonicalType);
4927 inline bool Type::isDependentSizedArrayType() const {
4928 return isa<DependentSizedArrayType>(CanonicalType);
4930 inline bool Type::isBuiltinType() const {
4931 return isa<BuiltinType>(CanonicalType);
4933 inline bool Type::isRecordType() const {
4934 return isa<RecordType>(CanonicalType);
4936 inline bool Type::isEnumeralType() const {
4937 return isa<EnumType>(CanonicalType);
4939 inline bool Type::isAnyComplexType() const {
4940 return isa<ComplexType>(CanonicalType);
4942 inline bool Type::isVectorType() const {
4943 return isa<VectorType>(CanonicalType);
4945 inline bool Type::isExtVectorType() const {
4946 return isa<ExtVectorType>(CanonicalType);
4948 inline bool Type::isObjCObjectPointerType() const {
4949 return isa<ObjCObjectPointerType>(CanonicalType);
4951 inline bool Type::isObjCObjectType() const {
4952 return isa<ObjCObjectType>(CanonicalType);
4954 inline bool Type::isObjCObjectOrInterfaceType() const {
4955 return isa<ObjCInterfaceType>(CanonicalType) ||
4956 isa<ObjCObjectType>(CanonicalType);
4958 inline bool Type::isAtomicType() const {
4959 return isa<AtomicType>(CanonicalType);
4962 inline bool Type::isObjCQualifiedIdType() const {
4963 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4964 return OPT->isObjCQualifiedIdType();
4967 inline bool Type::isObjCQualifiedClassType() const {
4968 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4969 return OPT->isObjCQualifiedClassType();
4972 inline bool Type::isObjCIdType() const {
4973 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4974 return OPT->isObjCIdType();
4977 inline bool Type::isObjCClassType() const {
4978 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4979 return OPT->isObjCClassType();
4982 inline bool Type::isObjCSelType() const {
4983 if (const PointerType *OPT = getAs<PointerType>())
4984 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4987 inline bool Type::isObjCBuiltinType() const {
4988 return isObjCIdType() || isObjCClassType() || isObjCSelType();
4991 inline bool Type::isImage1dT() const {
4992 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
4995 inline bool Type::isImage1dArrayT() const {
4996 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
4999 inline bool Type::isImage1dBufferT() const {
5000 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
5003 inline bool Type::isImage2dT() const {
5004 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
5007 inline bool Type::isImage2dArrayT() const {
5008 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
5011 inline bool Type::isImage3dT() const {
5012 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
5015 inline bool Type::isSamplerT() const {
5016 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5019 inline bool Type::isEventT() const {
5020 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5023 inline bool Type::isImageType() const {
5024 return isImage3dT() ||
5025 isImage2dT() || isImage2dArrayT() ||
5026 isImage1dT() || isImage1dArrayT() || isImage1dBufferT();
5029 inline bool Type::isOpenCLSpecificType() const {
5030 return isSamplerT() || isEventT() || isImageType();
5033 inline bool Type::isTemplateTypeParmType() const {
5034 return isa<TemplateTypeParmType>(CanonicalType);
5037 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5038 if (const BuiltinType *BT = getAs<BuiltinType>())
5039 if (BT->getKind() == (BuiltinType::Kind) K)
5044 inline bool Type::isPlaceholderType() const {
5045 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5046 return BT->isPlaceholderType();
5050 inline const BuiltinType *Type::getAsPlaceholderType() const {
5051 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5052 if (BT->isPlaceholderType())
5057 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5058 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5059 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5060 return (BT->getKind() == (BuiltinType::Kind) K);
5064 inline bool Type::isNonOverloadPlaceholderType() const {
5065 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5066 return BT->isNonOverloadPlaceholderType();
5070 inline bool Type::isVoidType() const {
5071 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5072 return BT->getKind() == BuiltinType::Void;
5076 inline bool Type::isHalfType() const {
5077 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5078 return BT->getKind() == BuiltinType::Half;
5079 // FIXME: Should we allow complex __fp16? Probably not.
5083 inline bool Type::isNullPtrType() const {
5084 if (const BuiltinType *BT = getAs<BuiltinType>())
5085 return BT->getKind() == BuiltinType::NullPtr;
5089 extern bool IsEnumDeclComplete(EnumDecl *);
5090 extern bool IsEnumDeclScoped(EnumDecl *);
5092 inline bool Type::isIntegerType() const {
5093 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5094 return BT->getKind() >= BuiltinType::Bool &&
5095 BT->getKind() <= BuiltinType::Int128;
5096 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5097 // Incomplete enum types are not treated as integer types.
5098 // FIXME: In C++, enum types are never integer types.
5099 return IsEnumDeclComplete(ET->getDecl()) &&
5100 !IsEnumDeclScoped(ET->getDecl());
5105 inline bool Type::isScalarType() const {
5106 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5107 return BT->getKind() > BuiltinType::Void &&
5108 BT->getKind() <= BuiltinType::NullPtr;
5109 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5110 // Enums are scalar types, but only if they are defined. Incomplete enums
5111 // are not treated as scalar types.
5112 return IsEnumDeclComplete(ET->getDecl());
5113 return isa<PointerType>(CanonicalType) ||
5114 isa<BlockPointerType>(CanonicalType) ||
5115 isa<MemberPointerType>(CanonicalType) ||
5116 isa<ComplexType>(CanonicalType) ||
5117 isa<ObjCObjectPointerType>(CanonicalType);
5120 inline bool Type::isIntegralOrEnumerationType() const {
5121 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5122 return BT->getKind() >= BuiltinType::Bool &&
5123 BT->getKind() <= BuiltinType::Int128;
5125 // Check for a complete enum type; incomplete enum types are not properly an
5126 // enumeration type in the sense required here.
5127 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5128 return IsEnumDeclComplete(ET->getDecl());
5133 inline bool Type::isBooleanType() const {
5134 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5135 return BT->getKind() == BuiltinType::Bool;
5139 inline bool Type::isUndeducedType() const {
5140 const AutoType *AT = getContainedAutoType();
5141 return AT && !AT->isDeduced();
5144 /// \brief Determines whether this is a type for which one can define
5145 /// an overloaded operator.
5146 inline bool Type::isOverloadableType() const {
5147 return isDependentType() || isRecordType() || isEnumeralType();
5150 /// \brief Determines whether this type can decay to a pointer type.
5151 inline bool Type::canDecayToPointerType() const {
5152 return isFunctionType() || isArrayType();
5155 inline bool Type::hasPointerRepresentation() const {
5156 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5157 isObjCObjectPointerType() || isNullPtrType());
5160 inline bool Type::hasObjCPointerRepresentation() const {
5161 return isObjCObjectPointerType();
5164 inline const Type *Type::getBaseElementTypeUnsafe() const {
5165 const Type *type = this;
5166 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5167 type = arrayType->getElementType().getTypePtr();
5171 /// Insertion operator for diagnostics. This allows sending QualType's into a
5172 /// diagnostic with <<.
5173 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5175 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5176 DiagnosticsEngine::ak_qualtype);
5180 /// Insertion operator for partial diagnostics. This allows sending QualType's
5181 /// into a diagnostic with <<.
5182 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5184 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5185 DiagnosticsEngine::ak_qualtype);
5189 // Helper class template that is used by Type::getAs to ensure that one does
5190 // not try to look through a qualified type to get to an array type.
5191 template <typename T, bool isArrayType = (std::is_same<T, ArrayType>::value ||
5192 std::is_base_of<ArrayType, T>::value)>
5193 struct ArrayType_cannot_be_used_with_getAs {};
5195 template<typename T>
5196 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5198 // Member-template getAs<specific type>'.
5199 template <typename T> const T *Type::getAs() const {
5200 ArrayType_cannot_be_used_with_getAs<T> at;
5203 // If this is directly a T type, return it.
5204 if (const T *Ty = dyn_cast<T>(this))
5207 // If the canonical form of this type isn't the right kind, reject it.
5208 if (!isa<T>(CanonicalType))
5211 // If this is a typedef for the type, strip the typedef off without
5212 // losing all typedef information.
5213 return cast<T>(getUnqualifiedDesugaredType());
5216 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5217 // If this is directly an array type, return it.
5218 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5221 // If the canonical form of this type isn't the right kind, reject it.
5222 if (!isa<ArrayType>(CanonicalType))
5225 // If this is a typedef for the type, strip the typedef off without
5226 // losing all typedef information.
5227 return cast<ArrayType>(getUnqualifiedDesugaredType());
5230 template <typename T> const T *Type::castAs() const {
5231 ArrayType_cannot_be_used_with_getAs<T> at;
5234 assert(isa<T>(CanonicalType));
5235 if (const T *ty = dyn_cast<T>(this)) return ty;
5236 return cast<T>(getUnqualifiedDesugaredType());
5239 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5240 assert(isa<ArrayType>(CanonicalType));
5241 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5242 return cast<ArrayType>(getUnqualifiedDesugaredType());
5245 } // end namespace clang