clang 17.0.0git
Type.h
Go to the documentation of this file.
1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/PointerIntPair.h"
38#include "llvm/ADT/PointerUnion.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/Twine.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/PointerLikeTypeTraits.h"
46#include "llvm/Support/TrailingObjects.h"
47#include "llvm/Support/type_traits.h"
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51#include <cstring>
52#include <optional>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class BTFTypeTagAttr;
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
83 template<>
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132class UsingShadowDecl;
133
134using CanQualType = CanQual<Type>;
135
136// Provide forward declarations for all of the *Type classes.
137#define TYPE(Class, Base) class Class##Type;
138#include "clang/AST/TypeNodes.inc"
139
140/// The collection of all-type qualifiers we support.
141/// Clang supports five independent qualifiers:
142/// * C99: const, volatile, and restrict
143/// * MS: __unaligned
144/// * Embedded C (TR18037): address spaces
145/// * Objective C: the GC attributes (none, weak, or strong)
147public:
148 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
149 Const = 0x1,
150 Restrict = 0x2,
151 Volatile = 0x4,
153 };
154
155 enum GC {
158 Strong
159 };
160
162 /// There is no lifetime qualification on this type.
164
165 /// This object can be modified without requiring retains or
166 /// releases.
168
169 /// Assigning into this object requires the old value to be
170 /// released and the new value to be retained. The timing of the
171 /// release of the old value is inexact: it may be moved to
172 /// immediately after the last known point where the value is
173 /// live.
175
176 /// Reading or writing from this object requires a barrier call.
178
179 /// Assigning into this object requires a lifetime extension.
181 };
182
183 enum {
184 /// The maximum supported address space number.
185 /// 23 bits should be enough for anyone.
186 MaxAddressSpace = 0x7fffffu,
187
188 /// The width of the "fast" qualifier mask.
190
191 /// The fast qualifier mask.
192 FastMask = (1 << FastWidth) - 1
193 };
194
195 /// Returns the common set of qualifiers while removing them from
196 /// the given sets.
198 // If both are only CVR-qualified, bit operations are sufficient.
199 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
200 Qualifiers Q;
201 Q.Mask = L.Mask & R.Mask;
202 L.Mask &= ~Q.Mask;
203 R.Mask &= ~Q.Mask;
204 return Q;
205 }
206
207 Qualifiers Q;
208 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
209 Q.addCVRQualifiers(CommonCRV);
210 L.removeCVRQualifiers(CommonCRV);
211 R.removeCVRQualifiers(CommonCRV);
212
213 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
217 }
218
219 if (L.getObjCLifetime() == R.getObjCLifetime()) {
223 }
224
225 if (L.getAddressSpace() == R.getAddressSpace()) {
229 }
230 return Q;
231 }
232
233 static Qualifiers fromFastMask(unsigned Mask) {
234 Qualifiers Qs;
235 Qs.addFastQualifiers(Mask);
236 return Qs;
237 }
238
239 static Qualifiers fromCVRMask(unsigned CVR) {
240 Qualifiers Qs;
241 Qs.addCVRQualifiers(CVR);
242 return Qs;
243 }
244
245 static Qualifiers fromCVRUMask(unsigned CVRU) {
246 Qualifiers Qs;
247 Qs.addCVRUQualifiers(CVRU);
248 return Qs;
249 }
250
251 // Deserialize qualifiers from an opaque representation.
252 static Qualifiers fromOpaqueValue(unsigned opaque) {
253 Qualifiers Qs;
254 Qs.Mask = opaque;
255 return Qs;
256 }
257
258 // Serialize these qualifiers into an opaque representation.
259 unsigned getAsOpaqueValue() const {
260 return Mask;
261 }
262
263 bool hasConst() const { return Mask & Const; }
264 bool hasOnlyConst() const { return Mask == Const; }
265 void removeConst() { Mask &= ~Const; }
266 void addConst() { Mask |= Const; }
268 Qualifiers Qs = *this;
269 Qs.addConst();
270 return Qs;
271 }
272
273 bool hasVolatile() const { return Mask & Volatile; }
274 bool hasOnlyVolatile() const { return Mask == Volatile; }
275 void removeVolatile() { Mask &= ~Volatile; }
276 void addVolatile() { Mask |= Volatile; }
278 Qualifiers Qs = *this;
279 Qs.addVolatile();
280 return Qs;
281 }
282
283 bool hasRestrict() const { return Mask & Restrict; }
284 bool hasOnlyRestrict() const { return Mask == Restrict; }
285 void removeRestrict() { Mask &= ~Restrict; }
286 void addRestrict() { Mask |= Restrict; }
288 Qualifiers Qs = *this;
289 Qs.addRestrict();
290 return Qs;
291 }
292
293 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
294 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
295 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
296
297 void setCVRQualifiers(unsigned mask) {
298 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
299 Mask = (Mask & ~CVRMask) | mask;
300 }
301 void removeCVRQualifiers(unsigned mask) {
302 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
303 Mask &= ~mask;
304 }
307 }
308 void addCVRQualifiers(unsigned mask) {
309 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
310 Mask |= mask;
311 }
312 void addCVRUQualifiers(unsigned mask) {
313 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
314 Mask |= mask;
315 }
316
317 bool hasUnaligned() const { return Mask & UMask; }
318 void setUnaligned(bool flag) {
319 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
320 }
321 void removeUnaligned() { Mask &= ~UMask; }
322 void addUnaligned() { Mask |= UMask; }
323
324 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
325 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
327 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
328 }
331 assert(type);
333 }
335 Qualifiers qs = *this;
336 qs.removeObjCGCAttr();
337 return qs;
338 }
340 Qualifiers qs = *this;
342 return qs;
343 }
345 Qualifiers qs = *this;
347 return qs;
348 }
349
350 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
352 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
353 }
355 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
356 }
359 assert(type);
360 assert(!hasObjCLifetime());
361 Mask |= (type << LifetimeShift);
362 }
363
364 /// True if the lifetime is neither None or ExplicitNone.
366 ObjCLifetime lifetime = getObjCLifetime();
367 return (lifetime > OCL_ExplicitNone);
368 }
369
370 /// True if the lifetime is either strong or weak.
372 ObjCLifetime lifetime = getObjCLifetime();
373 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
374 }
375
376 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
378 return static_cast<LangAS>(Mask >> AddressSpaceShift);
379 }
382 }
383 /// Get the address space attribute value to be printed by diagnostics.
385 auto Addr = getAddressSpace();
386 // This function is not supposed to be used with language specific
387 // address spaces. If that happens, the diagnostic message should consider
388 // printing the QualType instead of the address space value.
390 if (Addr != LangAS::Default)
391 return toTargetAddressSpace(Addr);
392 // TODO: The diagnostic messages where Addr may be 0 should be fixed
393 // since it cannot differentiate the situation where 0 denotes the default
394 // address space or user specified __attribute__((address_space(0))).
395 return 0;
396 }
398 assert((unsigned)space <= MaxAddressSpace);
399 Mask = (Mask & ~AddressSpaceMask)
400 | (((uint32_t) space) << AddressSpaceShift);
401 }
404 assert(space != LangAS::Default);
405 setAddressSpace(space);
406 }
407
408 // Fast qualifiers are those that can be allocated directly
409 // on a QualType object.
410 bool hasFastQualifiers() const { return getFastQualifiers(); }
411 unsigned getFastQualifiers() const { return Mask & FastMask; }
412 void setFastQualifiers(unsigned mask) {
413 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
414 Mask = (Mask & ~FastMask) | mask;
415 }
416 void removeFastQualifiers(unsigned mask) {
417 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
418 Mask &= ~mask;
419 }
422 }
423 void addFastQualifiers(unsigned mask) {
424 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
425 Mask |= mask;
426 }
427
428 /// Return true if the set contains any qualifiers which require an ExtQuals
429 /// node to be allocated.
430 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
432 Qualifiers Quals = *this;
433 Quals.setFastQualifiers(0);
434 return Quals;
435 }
436
437 /// Return true if the set contains any qualifiers.
438 bool hasQualifiers() const { return Mask; }
439 bool empty() const { return !Mask; }
440
441 /// Add the qualifiers from the given set to this set.
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-or it in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask |= Q.Mask;
447 else {
448 Mask |= (Q.Mask & CVRMask);
449 if (Q.hasAddressSpace())
451 if (Q.hasObjCGCAttr())
453 if (Q.hasObjCLifetime())
455 }
456 }
457
458 /// Remove the qualifiers from the given set from this set.
460 // If the other set doesn't have any non-boolean qualifiers, just
461 // bit-and the inverse in.
462 if (!(Q.Mask & ~CVRMask))
463 Mask &= ~Q.Mask;
464 else {
465 Mask &= ~(Q.Mask & CVRMask);
466 if (getObjCGCAttr() == Q.getObjCGCAttr())
468 if (getObjCLifetime() == Q.getObjCLifetime())
470 if (getAddressSpace() == Q.getAddressSpace())
472 }
473 }
474
475 /// Add the qualifiers from the given set to this set, given that
476 /// they don't conflict.
478 assert(getAddressSpace() == qs.getAddressSpace() ||
479 !hasAddressSpace() || !qs.hasAddressSpace());
480 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
481 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
482 assert(getObjCLifetime() == qs.getObjCLifetime() ||
483 !hasObjCLifetime() || !qs.hasObjCLifetime());
484 Mask |= qs.Mask;
485 }
486
487 /// Returns true if address space A is equal to or a superset of B.
488 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
489 /// overlapping address spaces.
490 /// CL1.1 or CL1.2:
491 /// every address space is a superset of itself.
492 /// CL2.0 adds:
493 /// __generic is a superset of any address space except for __constant.
495 // Address spaces must match exactly.
496 return A == B ||
497 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
498 // for __constant can be used as __generic.
500 // We also define global_device and global_host address spaces,
501 // to distinguish global pointers allocated on host from pointers
502 // allocated on device, which are a subset of __global.
507 // Consider pointer size address spaces to be equivalent to default.
510 // Default is a superset of SYCL address spaces.
511 (A == LangAS::Default &&
515 // In HIP device compilation, any cuda address space is allowed
516 // to implicitly cast into the default address space.
517 (A == LangAS::Default &&
519 B == LangAS::cuda_shared));
520 }
521
522 /// Returns true if the address space in these qualifiers is equal to or
523 /// a superset of the address space in the argument qualifiers.
526 }
527
528 /// Determines if these qualifiers compatibly include another set.
529 /// Generally this answers the question of whether an object with the other
530 /// qualifiers can be safely used as an object with these qualifiers.
531 bool compatiblyIncludes(Qualifiers other) const {
532 return isAddressSpaceSupersetOf(other) &&
533 // ObjC GC qualifiers can match, be added, or be removed, but can't
534 // be changed.
535 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
536 !other.hasObjCGCAttr()) &&
537 // ObjC lifetime qualifiers must match exactly.
538 getObjCLifetime() == other.getObjCLifetime() &&
539 // CVR qualifiers may subset.
540 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
541 // U qualifier may superset.
542 (!other.hasUnaligned() || hasUnaligned());
543 }
544
545 /// Determines if these qualifiers compatibly include another set of
546 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
547 ///
548 /// One set of Objective-C lifetime qualifiers compatibly includes the other
549 /// if the lifetime qualifiers match, or if both are non-__weak and the
550 /// including set also contains the 'const' qualifier, or both are non-__weak
551 /// and one is None (which can only happen in non-ARC modes).
553 if (getObjCLifetime() == other.getObjCLifetime())
554 return true;
555
556 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
557 return false;
558
559 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
560 return true;
561
562 return hasConst();
563 }
564
565 /// Determine whether this set of qualifiers is a strict superset of
566 /// another set of qualifiers, not considering qualifier compatibility.
567 bool isStrictSupersetOf(Qualifiers Other) const;
568
569 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
570 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
571
572 explicit operator bool() const { return hasQualifiers(); }
573
575 addQualifiers(R);
576 return *this;
577 }
578
579 // Union two qualifier sets. If an enumerated qualifier appears
580 // in both sets, use the one from the right.
582 L += R;
583 return L;
584 }
585
588 return *this;
589 }
590
591 /// Compute the difference between two qualifier sets.
593 L -= R;
594 return L;
595 }
596
597 std::string getAsString() const;
598 std::string getAsString(const PrintingPolicy &Policy) const;
599
600 static std::string getAddrSpaceAsString(LangAS AS);
601
602 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
603 void print(raw_ostream &OS, const PrintingPolicy &Policy,
604 bool appendSpaceIfNonEmpty = false) const;
605
606 void Profile(llvm::FoldingSetNodeID &ID) const {
607 ID.AddInteger(Mask);
608 }
609
610private:
611 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
612 // |C R V|U|GCAttr|Lifetime|AddressSpace|
613 uint32_t Mask = 0;
614
615 static const uint32_t UMask = 0x8;
616 static const uint32_t UShift = 3;
617 static const uint32_t GCAttrMask = 0x30;
618 static const uint32_t GCAttrShift = 4;
619 static const uint32_t LifetimeMask = 0x1C0;
620 static const uint32_t LifetimeShift = 6;
621 static const uint32_t AddressSpaceMask =
622 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
623 static const uint32_t AddressSpaceShift = 9;
624};
625
627 Qualifiers Quals;
628 bool HasAtomic;
629
630public:
631 QualifiersAndAtomic() : HasAtomic(false) {}
632 QualifiersAndAtomic(Qualifiers Quals, bool HasAtomic)
633 : Quals(Quals), HasAtomic(HasAtomic) {}
634
635 operator Qualifiers() const { return Quals; }
636
637 bool hasVolatile() const { return Quals.hasVolatile(); }
638 bool hasConst() const { return Quals.hasConst(); }
639 bool hasRestrict() const { return Quals.hasRestrict(); }
640 bool hasAtomic() const { return HasAtomic; }
641
642 void addVolatile() { Quals.addVolatile(); }
643 void addConst() { Quals.addConst(); }
644 void addRestrict() { Quals.addRestrict(); }
645 void addAtomic() { HasAtomic = true; }
646
647 void removeVolatile() { Quals.removeVolatile(); }
648 void removeConst() { Quals.removeConst(); }
649 void removeRestrict() { Quals.removeRestrict(); }
650 void removeAtomic() { HasAtomic = false; }
651
653 return {Quals.withVolatile(), HasAtomic};
654 }
655 QualifiersAndAtomic withConst() { return {Quals.withConst(), HasAtomic}; }
657 return {Quals.withRestrict(), HasAtomic};
658 }
659 QualifiersAndAtomic withAtomic() { return {Quals, true}; }
660
662 Quals += RHS;
663 return *this;
664 }
665};
666
667/// A std::pair-like structure for storing a qualified type split
668/// into its local qualifiers and its locally-unqualified type.
670 /// The locally-unqualified type.
671 const Type *Ty = nullptr;
672
673 /// The local qualifiers.
675
676 SplitQualType() = default;
677 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
678
679 SplitQualType getSingleStepDesugaredType() const; // end of this file
680
681 // Make std::tie work.
682 std::pair<const Type *,Qualifiers> asPair() const {
683 return std::pair<const Type *, Qualifiers>(Ty, Quals);
684 }
685
687 return a.Ty == b.Ty && a.Quals == b.Quals;
688 }
690 return a.Ty != b.Ty || a.Quals != b.Quals;
691 }
692};
693
694/// The kind of type we are substituting Objective-C type arguments into.
695///
696/// The kind of substitution affects the replacement of type parameters when
697/// no concrete type information is provided, e.g., when dealing with an
698/// unspecialized type.
700 /// An ordinary type.
701 Ordinary,
702
703 /// The result type of a method or function.
704 Result,
705
706 /// The parameter type of a method or function.
707 Parameter,
708
709 /// The type of a property.
710 Property,
711
712 /// The superclass of a type.
714};
715
716/// The kind of 'typeof' expression we're after.
717enum class TypeOfKind : uint8_t {
718 Qualified,
720};
721
722/// A (possibly-)qualified type.
723///
724/// For efficiency, we don't store CV-qualified types as nodes on their
725/// own: instead each reference to a type stores the qualifiers. This
726/// greatly reduces the number of nodes we need to allocate for types (for
727/// example we only need one for 'int', 'const int', 'volatile int',
728/// 'const volatile int', etc).
729///
730/// As an added efficiency bonus, instead of making this a pair, we
731/// just store the two bits we care about in the low bits of the
732/// pointer. To handle the packing/unpacking, we make QualType be a
733/// simple wrapper class that acts like a smart pointer. A third bit
734/// indicates whether there are extended qualifiers present, in which
735/// case the pointer points to a special structure.
736class QualType {
737 friend class QualifierCollector;
738
739 // Thankfully, these are efficiently composable.
740 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
742
743 const ExtQuals *getExtQualsUnsafe() const {
744 return Value.getPointer().get<const ExtQuals*>();
745 }
746
747 const Type *getTypePtrUnsafe() const {
748 return Value.getPointer().get<const Type*>();
749 }
750
751 const ExtQualsTypeCommonBase *getCommonPtr() const {
752 assert(!isNull() && "Cannot retrieve a NULL type pointer");
753 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
754 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
755 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
756 }
757
758public:
759 QualType() = default;
760 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
761 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
762
763 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
764 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
765
766 bool UseExcessPrecision(const ASTContext &Ctx);
767
768 /// Retrieves a pointer to the underlying (unqualified) type.
769 ///
770 /// This function requires that the type not be NULL. If the type might be
771 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
772 const Type *getTypePtr() const;
773
774 const Type *getTypePtrOrNull() const;
775
776 /// Retrieves a pointer to the name of the base type.
778
779 /// Divides a QualType into its unqualified type and a set of local
780 /// qualifiers.
781 SplitQualType split() const;
782
783 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
784
785 static QualType getFromOpaquePtr(const void *Ptr) {
786 QualType T;
787 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
788 return T;
789 }
790
791 const Type &operator*() const {
792 return *getTypePtr();
793 }
794
795 const Type *operator->() const {
796 return getTypePtr();
797 }
798
799 bool isCanonical() const;
800 bool isCanonicalAsParam() const;
801
802 /// Return true if this QualType doesn't point to a type yet.
803 bool isNull() const {
804 return Value.getPointer().isNull();
805 }
806
807 // Determines if a type can form `T&`.
808 bool isReferenceable() const;
809
810 /// Determine whether this particular QualType instance has the
811 /// "const" qualifier set, without looking through typedefs that may have
812 /// added "const" at a different level.
815 }
816
817 /// Determine whether this type is const-qualified.
818 bool isConstQualified() const;
819
820 /// Determine whether this particular QualType instance has the
821 /// "restrict" qualifier set, without looking through typedefs that may have
822 /// added "restrict" at a different level.
825 }
826
827 /// Determine whether this type is restrict-qualified.
828 bool isRestrictQualified() const;
829
830 /// Determine whether this particular QualType instance has the
831 /// "volatile" qualifier set, without looking through typedefs that may have
832 /// added "volatile" at a different level.
835 }
836
837 /// Determine whether this type is volatile-qualified.
838 bool isVolatileQualified() const;
839
840 /// Determine whether this particular QualType instance has any
841 /// qualifiers, without looking through any typedefs that might add
842 /// qualifiers at a different level.
843 bool hasLocalQualifiers() const {
845 }
846
847 /// Determine whether this type has any qualifiers.
848 bool hasQualifiers() const;
849
850 /// Determine whether this particular QualType instance has any
851 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
852 /// instance.
854 return Value.getPointer().is<const ExtQuals*>();
855 }
856
857 /// Retrieve the set of qualifiers local to this particular QualType
858 /// instance, not including any qualifiers acquired through typedefs or
859 /// other sugar.
861
862 /// Retrieve the set of qualifiers applied to this type.
864
865 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
866 /// local to this particular QualType instance, not including any qualifiers
867 /// acquired through typedefs or other sugar.
868 unsigned getLocalCVRQualifiers() const {
869 return getLocalFastQualifiers();
870 }
871
872 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
873 /// applied to this type.
874 unsigned getCVRQualifiers() const;
875
876 bool isConstant(const ASTContext& Ctx) const {
877 return QualType::isConstant(*this, Ctx);
878 }
879
880 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
881 bool isPODType(const ASTContext &Context) const;
882
883 /// Return true if this is a POD type according to the rules of the C++98
884 /// standard, regardless of the current compilation's language.
885 bool isCXX98PODType(const ASTContext &Context) const;
886
887 /// Return true if this is a POD type according to the more relaxed rules
888 /// of the C++11 standard, regardless of the current compilation's language.
889 /// (C++0x [basic.types]p9). Note that, unlike
890 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
891 bool isCXX11PODType(const ASTContext &Context) const;
892
893 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
894 bool isTrivialType(const ASTContext &Context) const;
895
896 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
897 bool isTriviallyCopyableType(const ASTContext &Context) const;
898
899 /// Return true if this is a trivially relocatable type.
900 bool isTriviallyRelocatableType(const ASTContext &Context) const;
901
902 /// Return true if this is a trivially equality comparable type.
903 bool isTriviallyEqualityComparableType(const ASTContext &Context) const;
904
905 /// Returns true if it is a class and it might be dynamic.
906 bool mayBeDynamicClass() const;
907
908 /// Returns true if it is not a class or if the class might not be dynamic.
909 bool mayBeNotDynamicClass() const;
910
911 // Don't promise in the API that anything besides 'const' can be
912 // easily added.
913
914 /// Add the `const` type qualifier to this QualType.
915 void addConst() {
917 }
920 }
921
922 /// Add the `volatile` type qualifier to this QualType.
923 void addVolatile() {
925 }
928 }
929
930 /// Add the `restrict` qualifier to this QualType.
931 void addRestrict() {
933 }
936 }
937
938 QualType withCVRQualifiers(unsigned CVR) const {
939 return withFastQualifiers(CVR);
940 }
941
942 void addFastQualifiers(unsigned TQs) {
943 assert(!(TQs & ~Qualifiers::FastMask)
944 && "non-fast qualifier bits set in mask!");
945 Value.setInt(Value.getInt() | TQs);
946 }
947
948 void removeLocalConst();
949 void removeLocalVolatile();
950 void removeLocalRestrict();
951
952 void removeLocalFastQualifiers() { Value.setInt(0); }
953 void removeLocalFastQualifiers(unsigned Mask) {
954 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
955 Value.setInt(Value.getInt() & ~Mask);
956 }
957
958 // Creates a type with the given qualifiers in addition to any
959 // qualifiers already on this type.
960 QualType withFastQualifiers(unsigned TQs) const {
961 QualType T = *this;
962 T.addFastQualifiers(TQs);
963 return T;
964 }
965
966 // Creates a type with exactly the given fast qualifiers, removing
967 // any existing fast qualifiers.
970 }
971
972 // Removes fast qualifiers, but leaves any extended qualifiers in place.
974 QualType T = *this;
976 return T;
977 }
978
980
981 /// Return this type with all of the instance-specific qualifiers
982 /// removed, but without removing any qualifiers that may have been applied
983 /// through typedefs.
985
986 /// Retrieve the unqualified variant of the given type,
987 /// removing as little sugar as possible.
988 ///
989 /// This routine looks through various kinds of sugar to find the
990 /// least-desugared type that is unqualified. For example, given:
991 ///
992 /// \code
993 /// typedef int Integer;
994 /// typedef const Integer CInteger;
995 /// typedef CInteger DifferenceType;
996 /// \endcode
997 ///
998 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
999 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
1000 ///
1001 /// The resulting type might still be qualified if it's sugar for an array
1002 /// type. To strip qualifiers even from within a sugared array type, use
1003 /// ASTContext::getUnqualifiedArrayType.
1004 ///
1005 /// Note: In C, the _Atomic qualifier is special (see C2x 6.2.5p29 for
1006 /// details), and it is not stripped by this function. Use
1007 /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic.
1008 inline QualType getUnqualifiedType() const;
1009
1010 /// Retrieve the unqualified variant of the given type, removing as little
1011 /// sugar as possible.
1012 ///
1013 /// Like getUnqualifiedType(), but also returns the set of
1014 /// qualifiers that were built up.
1015 ///
1016 /// The resulting type might still be qualified if it's sugar for an array
1017 /// type. To strip qualifiers even from within a sugared array type, use
1018 /// ASTContext::getUnqualifiedArrayType.
1020
1021 /// Determine whether this type is more qualified than the other
1022 /// given type, requiring exact equality for non-CVR qualifiers.
1023 bool isMoreQualifiedThan(QualType Other) const;
1024
1025 /// Determine whether this type is at least as qualified as the other
1026 /// given type, requiring exact equality for non-CVR qualifiers.
1027 bool isAtLeastAsQualifiedAs(QualType Other) const;
1028
1030
1031 /// Determine the type of a (typically non-lvalue) expression with the
1032 /// specified result type.
1033 ///
1034 /// This routine should be used for expressions for which the return type is
1035 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
1036 /// an lvalue. It removes a top-level reference (since there are no
1037 /// expressions of reference type) and deletes top-level cvr-qualifiers
1038 /// from non-class types (in C++) or all types (in C).
1039 QualType getNonLValueExprType(const ASTContext &Context) const;
1040
1041 /// Remove an outer pack expansion type (if any) from this type. Used as part
1042 /// of converting the type of a declaration to the type of an expression that
1043 /// references that expression. It's meaningless for an expression to have a
1044 /// pack expansion type.
1046
1047 /// Return the specified type with any "sugar" removed from
1048 /// the type. This takes off typedefs, typeof's etc. If the outer level of
1049 /// the type is already concrete, it returns it unmodified. This is similar
1050 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
1051 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
1052 /// concrete.
1053 ///
1054 /// Qualifiers are left in place.
1055 QualType getDesugaredType(const ASTContext &Context) const {
1056 return getDesugaredType(*this, Context);
1057 }
1058
1060 return getSplitDesugaredType(*this);
1061 }
1062
1063 /// Return the specified type with one level of "sugar" removed from
1064 /// the type.
1065 ///
1066 /// This routine takes off the first typedef, typeof, etc. If the outer level
1067 /// of the type is already concrete, it returns it unmodified.
1069 return getSingleStepDesugaredTypeImpl(*this, Context);
1070 }
1071
1072 /// Returns the specified type after dropping any
1073 /// outer-level parentheses.
1075 if (isa<ParenType>(*this))
1076 return QualType::IgnoreParens(*this);
1077 return *this;
1078 }
1079
1080 /// Indicate whether the specified types and qualifiers are identical.
1081 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1082 return LHS.Value == RHS.Value;
1083 }
1084 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1085 return LHS.Value != RHS.Value;
1086 }
1087 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1088 return LHS.Value < RHS.Value;
1089 }
1090
1091 static std::string getAsString(SplitQualType split,
1092 const PrintingPolicy &Policy) {
1093 return getAsString(split.Ty, split.Quals, Policy);
1094 }
1095 static std::string getAsString(const Type *ty, Qualifiers qs,
1096 const PrintingPolicy &Policy);
1097
1098 std::string getAsString() const;
1099 std::string getAsString(const PrintingPolicy &Policy) const;
1100
1101 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1102 const Twine &PlaceHolder = Twine(),
1103 unsigned Indentation = 0) const;
1104
1105 static void print(SplitQualType split, raw_ostream &OS,
1106 const PrintingPolicy &policy, const Twine &PlaceHolder,
1107 unsigned Indentation = 0) {
1108 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1109 }
1110
1111 static void print(const Type *ty, Qualifiers qs,
1112 raw_ostream &OS, const PrintingPolicy &policy,
1113 const Twine &PlaceHolder,
1114 unsigned Indentation = 0);
1115
1116 void getAsStringInternal(std::string &Str,
1117 const PrintingPolicy &Policy) const;
1118
1119 static void getAsStringInternal(SplitQualType split, std::string &out,
1120 const PrintingPolicy &policy) {
1121 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1122 }
1123
1124 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1125 std::string &out,
1126 const PrintingPolicy &policy);
1127
1129 const QualType &T;
1130 const PrintingPolicy &Policy;
1131 const Twine &PlaceHolder;
1132 unsigned Indentation;
1133
1134 public:
1136 const Twine &PlaceHolder, unsigned Indentation)
1137 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1138 Indentation(Indentation) {}
1139
1140 friend raw_ostream &operator<<(raw_ostream &OS,
1141 const StreamedQualTypeHelper &SQT) {
1142 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1143 return OS;
1144 }
1145 };
1146
1148 const Twine &PlaceHolder = Twine(),
1149 unsigned Indentation = 0) const {
1150 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1151 }
1152
1153 void dump(const char *s) const;
1154 void dump() const;
1155 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1156
1157 void Profile(llvm::FoldingSetNodeID &ID) const {
1158 ID.AddPointer(getAsOpaquePtr());
1159 }
1160
1161 /// Check if this type has any address space qualifier.
1162 inline bool hasAddressSpace() const;
1163
1164 /// Return the address space of this type.
1165 inline LangAS getAddressSpace() const;
1166
1167 /// Returns true if address space qualifiers overlap with T address space
1168 /// qualifiers.
1169 /// OpenCL C defines conversion rules for pointers to different address spaces
1170 /// and notion of overlapping address spaces.
1171 /// CL1.1 or CL1.2:
1172 /// address spaces overlap iff they are they same.
1173 /// OpenCL C v2.0 s6.5.5 adds:
1174 /// __generic overlaps with any address space except for __constant.
1177 Qualifiers TQ = T.getQualifiers();
1178 // Address spaces overlap if at least one of them is a superset of another
1180 }
1181
1182 /// Returns gc attribute of this type.
1183 inline Qualifiers::GC getObjCGCAttr() const;
1184
1185 /// true when Type is objc's weak.
1186 bool isObjCGCWeak() const {
1187 return getObjCGCAttr() == Qualifiers::Weak;
1188 }
1189
1190 /// true when Type is objc's strong.
1191 bool isObjCGCStrong() const {
1193 }
1194
1195 /// Returns lifetime attribute of this type.
1197 return getQualifiers().getObjCLifetime();
1198 }
1199
1202 }
1203
1206 }
1207
1208 // true when Type is objc's weak and weak is enabled but ARC isn't.
1209 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1210
1212 /// The type does not fall into any of the following categories. Note that
1213 /// this case is zero-valued so that values of this enum can be used as a
1214 /// boolean condition for non-triviality.
1216
1217 /// The type is an Objective-C retainable pointer type that is qualified
1218 /// with the ARC __strong qualifier.
1220
1221 /// The type is an Objective-C retainable pointer type that is qualified
1222 /// with the ARC __weak qualifier.
1224
1225 /// The type is a struct containing a field whose type is not PCK_Trivial.
1228
1229 /// Functions to query basic properties of non-trivial C struct types.
1230
1231 /// Check if this is a non-trivial type that would cause a C struct
1232 /// transitively containing this type to be non-trivial to default initialize
1233 /// and return the kind.
1236
1238 /// The type does not fall into any of the following categories. Note that
1239 /// this case is zero-valued so that values of this enum can be used as a
1240 /// boolean condition for non-triviality.
1242
1243 /// The type would be trivial except that it is volatile-qualified. Types
1244 /// that fall into one of the other non-trivial cases may additionally be
1245 /// volatile-qualified.
1247
1248 /// The type is an Objective-C retainable pointer type that is qualified
1249 /// with the ARC __strong qualifier.
1251
1252 /// The type is an Objective-C retainable pointer type that is qualified
1253 /// with the ARC __weak qualifier.
1255
1256 /// The type is a struct containing a field whose type is neither
1257 /// PCK_Trivial nor PCK_VolatileTrivial.
1258 /// Note that a C++ struct type does not necessarily match this; C++ copying
1259 /// semantics are too complex to express here, in part because they depend
1260 /// on the exact constructor or assignment operator that is chosen by
1261 /// overload resolution to do the copy.
1264
1265 /// Check if this is a non-trivial type that would cause a C struct
1266 /// transitively containing this type to be non-trivial to copy and return the
1267 /// kind.
1269
1270 /// Check if this is a non-trivial type that would cause a C struct
1271 /// transitively containing this type to be non-trivial to destructively
1272 /// move and return the kind. Destructive move in this context is a C++-style
1273 /// move in which the source object is placed in a valid but unspecified state
1274 /// after it is moved, as opposed to a truly destructive move in which the
1275 /// source object is placed in an uninitialized state.
1277
1285
1286 /// Returns a nonzero value if objects of this type require
1287 /// non-trivial work to clean up after. Non-zero because it's
1288 /// conceivable that qualifiers (objc_gc(weak)?) could make
1289 /// something require destruction.
1291 return isDestructedTypeImpl(*this);
1292 }
1293
1294 /// Check if this is or contains a C union that is non-trivial to
1295 /// default-initialize, which is a union that has a member that is non-trivial
1296 /// to default-initialize. If this returns true,
1297 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1299
1300 /// Check if this is or contains a C union that is non-trivial to destruct,
1301 /// which is a union that has a member that is non-trivial to destruct. If
1302 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1304
1305 /// Check if this is or contains a C union that is non-trivial to copy, which
1306 /// is a union that has a member that is non-trivial to copy. If this returns
1307 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1309
1310 /// Determine whether expressions of the given type are forbidden
1311 /// from being lvalues in C.
1312 ///
1313 /// The expression types that are forbidden to be lvalues are:
1314 /// - 'void', but not qualified void
1315 /// - function types
1316 ///
1317 /// The exact rule here is C99 6.3.2.1:
1318 /// An lvalue is an expression with an object type or an incomplete
1319 /// type other than void.
1320 bool isCForbiddenLValueType() const;
1321
1322 /// Substitute type arguments for the Objective-C type parameters used in the
1323 /// subject type.
1324 ///
1325 /// \param ctx ASTContext in which the type exists.
1326 ///
1327 /// \param typeArgs The type arguments that will be substituted for the
1328 /// Objective-C type parameters in the subject type, which are generally
1329 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1330 /// parameters will be replaced with their bounds or id/Class, as appropriate
1331 /// for the context.
1332 ///
1333 /// \param context The context in which the subject type was written.
1334 ///
1335 /// \returns the resulting type.
1337 ArrayRef<QualType> typeArgs,
1338 ObjCSubstitutionContext context) const;
1339
1340 /// Substitute type arguments from an object type for the Objective-C type
1341 /// parameters used in the subject type.
1342 ///
1343 /// This operation combines the computation of type arguments for
1344 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1345 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1346 /// callers that need to perform a single substitution in isolation.
1347 ///
1348 /// \param objectType The type of the object whose member type we're
1349 /// substituting into. For example, this might be the receiver of a message
1350 /// or the base of a property access.
1351 ///
1352 /// \param dc The declaration context from which the subject type was
1353 /// retrieved, which indicates (for example) which type parameters should
1354 /// be substituted.
1355 ///
1356 /// \param context The context in which the subject type was written.
1357 ///
1358 /// \returns the subject type after replacing all of the Objective-C type
1359 /// parameters with their corresponding arguments.
1361 const DeclContext *dc,
1362 ObjCSubstitutionContext context) const;
1363
1364 /// Strip Objective-C "__kindof" types from the given type.
1365 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1366
1367 /// Remove all qualifiers including _Atomic.
1369
1370private:
1371 // These methods are implemented in a separate translation unit;
1372 // "static"-ize them to avoid creating temporary QualTypes in the
1373 // caller.
1374 static bool isConstant(QualType T, const ASTContext& Ctx);
1375 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1377 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1378 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1379 const ASTContext &C);
1380 static QualType IgnoreParens(QualType T);
1381 static DestructionKind isDestructedTypeImpl(QualType type);
1382
1383 /// Check if \param RD is or contains a non-trivial C union.
1386 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1387};
1388
1389raw_ostream &operator<<(raw_ostream &OS, QualType QT);
1390
1391} // namespace clang
1392
1393namespace llvm {
1394
1395/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1396/// to a specific Type class.
1397template<> struct simplify_type< ::clang::QualType> {
1398 using SimpleType = const ::clang::Type *;
1399
1401 return Val.getTypePtr();
1402 }
1403};
1404
1405// Teach SmallPtrSet that QualType is "basically a pointer".
1406template<>
1407struct PointerLikeTypeTraits<clang::QualType> {
1408 static inline void *getAsVoidPointer(clang::QualType P) {
1409 return P.getAsOpaquePtr();
1410 }
1411
1412 static inline clang::QualType getFromVoidPointer(void *P) {
1414 }
1415
1416 // Various qualifiers go in low bits.
1417 static constexpr int NumLowBitsAvailable = 0;
1418};
1419
1420} // namespace llvm
1421
1422namespace clang {
1423
1424/// Base class that is common to both the \c ExtQuals and \c Type
1425/// classes, which allows \c QualType to access the common fields between the
1426/// two.
1428 friend class ExtQuals;
1429 friend class QualType;
1430 friend class Type;
1431
1432 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1433 /// a self-referential pointer (for \c Type).
1434 ///
1435 /// This pointer allows an efficient mapping from a QualType to its
1436 /// underlying type pointer.
1437 const Type *const BaseType;
1438
1439 /// The canonical type of this type. A QualType.
1440 QualType CanonicalType;
1441
1442 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1443 : BaseType(baseType), CanonicalType(canon) {}
1444};
1445
1446/// We can encode up to four bits in the low bits of a
1447/// type pointer, but there are many more type qualifiers that we want
1448/// to be able to apply to an arbitrary type. Therefore we have this
1449/// struct, intended to be heap-allocated and used by QualType to
1450/// store qualifiers.
1451///
1452/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1453/// in three low bits on the QualType pointer; a fourth bit records whether
1454/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1455/// Objective-C GC attributes) are much more rare.
1456class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1457 // NOTE: changing the fast qualifiers should be straightforward as
1458 // long as you don't make 'const' non-fast.
1459 // 1. Qualifiers:
1460 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1461 // Fast qualifiers must occupy the low-order bits.
1462 // b) Update Qualifiers::FastWidth and FastMask.
1463 // 2. QualType:
1464 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1465 // b) Update remove{Volatile,Restrict}, defined near the end of
1466 // this header.
1467 // 3. ASTContext:
1468 // a) Update get{Volatile,Restrict}Type.
1469
1470 /// The immutable set of qualifiers applied by this node. Always contains
1471 /// extended qualifiers.
1472 Qualifiers Quals;
1473
1474 ExtQuals *this_() { return this; }
1475
1476public:
1477 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1478 : ExtQualsTypeCommonBase(baseType,
1479 canon.isNull() ? QualType(this_(), 0) : canon),
1480 Quals(quals) {
1481 assert(Quals.hasNonFastQualifiers()
1482 && "ExtQuals created with no fast qualifiers");
1483 assert(!Quals.hasFastQualifiers()
1484 && "ExtQuals created with fast qualifiers");
1485 }
1486
1487 Qualifiers getQualifiers() const { return Quals; }
1488
1489 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1490 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1491
1492 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1494 return Quals.getObjCLifetime();
1495 }
1496
1497 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1498 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1499
1500 const Type *getBaseType() const { return BaseType; }
1501
1502public:
1503 void Profile(llvm::FoldingSetNodeID &ID) const {
1504 Profile(ID, getBaseType(), Quals);
1505 }
1506
1507 static void Profile(llvm::FoldingSetNodeID &ID,
1508 const Type *BaseType,
1509 Qualifiers Quals) {
1510 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1511 ID.AddPointer(BaseType);
1512 Quals.Profile(ID);
1513 }
1514};
1515
1516/// The kind of C++11 ref-qualifier associated with a function type.
1517/// This determines whether a member function's "this" object can be an
1518/// lvalue, rvalue, or neither.
1520 /// No ref-qualifier was provided.
1522
1523 /// An lvalue ref-qualifier was provided (\c &).
1525
1526 /// An rvalue ref-qualifier was provided (\c &&).
1527 RQ_RValue
1529
1530/// Which keyword(s) were used to create an AutoType.
1532 /// auto
1533 Auto,
1534
1535 /// decltype(auto)
1537
1538 /// __auto_type (GNU extension)
1540};
1541
1542/// The base class of the type hierarchy.
1543///
1544/// A central concept with types is that each type always has a canonical
1545/// type. A canonical type is the type with any typedef names stripped out
1546/// of it or the types it references. For example, consider:
1547///
1548/// typedef int foo;
1549/// typedef foo* bar;
1550/// 'int *' 'foo *' 'bar'
1551///
1552/// There will be a Type object created for 'int'. Since int is canonical, its
1553/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1554/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1555/// there is a PointerType that represents 'int*', which, like 'int', is
1556/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1557/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1558/// is also 'int*'.
1559///
1560/// Non-canonical types are useful for emitting diagnostics, without losing
1561/// information about typedefs being used. Canonical types are useful for type
1562/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1563/// about whether something has a particular form (e.g. is a function type),
1564/// because they implicitly, recursively, strip all typedefs out of a type.
1565///
1566/// Types, once created, are immutable.
1567///
1568class alignas(8) Type : public ExtQualsTypeCommonBase {
1569public:
1571#define TYPE(Class, Base) Class,
1572#define LAST_TYPE(Class) TypeLast = Class
1573#define ABSTRACT_TYPE(Class, Base)
1574#include "clang/AST/TypeNodes.inc"
1575 };
1576
1577private:
1578 /// Bitfields required by the Type class.
1579 class TypeBitfields {
1580 friend class Type;
1581 template <class T> friend class TypePropertyCache;
1582
1583 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1584 unsigned TC : 8;
1585
1586 /// Store information on the type dependency.
1587 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1588
1589 /// True if the cache (i.e. the bitfields here starting with
1590 /// 'Cache') is valid.
1591 mutable unsigned CacheValid : 1;
1592
1593 /// Linkage of this type.
1594 mutable unsigned CachedLinkage : 3;
1595
1596 /// Whether this type involves and local or unnamed types.
1597 mutable unsigned CachedLocalOrUnnamed : 1;
1598
1599 /// Whether this type comes from an AST file.
1600 mutable unsigned FromAST : 1;
1601
1602 bool isCacheValid() const {
1603 return CacheValid;
1604 }
1605
1606 Linkage getLinkage() const {
1607 assert(isCacheValid() && "getting linkage from invalid cache");
1608 return static_cast<Linkage>(CachedLinkage);
1609 }
1610
1611 bool hasLocalOrUnnamedType() const {
1612 assert(isCacheValid() && "getting linkage from invalid cache");
1613 return CachedLocalOrUnnamed;
1614 }
1615 };
1616 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1617
1618protected:
1619 // These classes allow subclasses to somewhat cleanly pack bitfields
1620 // into Type.
1621
1623 friend class ArrayType;
1624
1625 unsigned : NumTypeBits;
1626
1627 /// CVR qualifiers from declarations like
1628 /// 'int X[static restrict 4]'. For function parameters only.
1629 unsigned IndexTypeQuals : 3;
1630
1631 /// Storage class qualifiers from declarations like
1632 /// 'int X[static restrict 4]'. For function parameters only.
1633 /// Actually an ArrayType::ArraySizeModifier.
1634 unsigned SizeModifier : 3;
1635 };
1636
1638 friend class ConstantArrayType;
1639
1640 unsigned : NumTypeBits + 3 + 3;
1641
1642 /// Whether we have a stored size expression.
1643 unsigned HasStoredSizeExpr : 1;
1644 };
1645
1647 friend class BuiltinType;
1648
1649 unsigned : NumTypeBits;
1650
1651 /// The kind (BuiltinType::Kind) of builtin type this is.
1652 unsigned Kind : 8;
1653 };
1654
1655 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1656 /// Only common bits are stored here. Additional uncommon bits are stored
1657 /// in a trailing object after FunctionProtoType.
1659 friend class FunctionProtoType;
1660 friend class FunctionType;
1661
1662 unsigned : NumTypeBits;
1663
1664 /// Extra information which affects how the function is called, like
1665 /// regparm and the calling convention.
1666 unsigned ExtInfo : 13;
1667
1668 /// The ref-qualifier associated with a \c FunctionProtoType.
1669 ///
1670 /// This is a value of type \c RefQualifierKind.
1671 unsigned RefQualifier : 2;
1672
1673 /// Used only by FunctionProtoType, put here to pack with the
1674 /// other bitfields.
1675 /// The qualifiers are part of FunctionProtoType because...
1676 ///
1677 /// C++ 8.3.5p4: The return type, the parameter type list and the
1678 /// cv-qualifier-seq, [...], are part of the function type.
1679 unsigned FastTypeQuals : Qualifiers::FastWidth;
1680 /// Whether this function has extended Qualifiers.
1681 unsigned HasExtQuals : 1;
1682
1683 /// The number of parameters this function has, not counting '...'.
1684 /// According to [implimits] 8 bits should be enough here but this is
1685 /// somewhat easy to exceed with metaprogramming and so we would like to
1686 /// keep NumParams as wide as reasonably possible.
1687 unsigned NumParams : 16;
1688
1689 /// The type of exception specification this function has.
1690 unsigned ExceptionSpecType : 4;
1691
1692 /// Whether this function has extended parameter information.
1693 unsigned HasExtParameterInfos : 1;
1694
1695 /// Whether this function has extra bitfields for the prototype.
1696 unsigned HasExtraBitfields : 1;
1697
1698 /// Whether the function is variadic.
1699 unsigned Variadic : 1;
1700
1701 /// Whether this function has a trailing return type.
1702 unsigned HasTrailingReturn : 1;
1703 };
1704
1706 friend class ObjCObjectType;
1707
1708 unsigned : NumTypeBits;
1709
1710 /// The number of type arguments stored directly on this object type.
1711 unsigned NumTypeArgs : 7;
1712
1713 /// The number of protocols stored directly on this object type.
1714 unsigned NumProtocols : 6;
1715
1716 /// Whether this is a "kindof" type.
1717 unsigned IsKindOf : 1;
1718 };
1719
1721 friend class ReferenceType;
1722
1723 unsigned : NumTypeBits;
1724
1725 /// True if the type was originally spelled with an lvalue sigil.
1726 /// This is never true of rvalue references but can also be false
1727 /// on lvalue references because of C++0x [dcl.typedef]p9,
1728 /// as follows:
1729 ///
1730 /// typedef int &ref; // lvalue, spelled lvalue
1731 /// typedef int &&rvref; // rvalue
1732 /// ref &a; // lvalue, inner ref, spelled lvalue
1733 /// ref &&a; // lvalue, inner ref
1734 /// rvref &a; // lvalue, inner ref, spelled lvalue
1735 /// rvref &&a; // rvalue, inner ref
1736 unsigned SpelledAsLValue : 1;
1737
1738 /// True if the inner type is a reference type. This only happens
1739 /// in non-canonical forms.
1740 unsigned InnerRef : 1;
1741 };
1742
1744 friend class TypeWithKeyword;
1745
1746 unsigned : NumTypeBits;
1747
1748 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1749 unsigned Keyword : 8;
1750 };
1751
1753
1755 friend class ElaboratedType;
1756
1757 unsigned : NumTypeBits;
1759
1760 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1761 unsigned HasOwnedTagDecl : 1;
1762 };
1763
1765 friend class VectorType;
1767
1768 unsigned : NumTypeBits;
1769
1770 /// The kind of vector, either a generic vector type or some
1771 /// target-specific vector type such as for AltiVec or Neon.
1772 unsigned VecKind : 4;
1773 /// The number of elements in the vector.
1774 uint32_t NumElements;
1775 };
1776
1778 friend class AttributedType;
1779
1780 unsigned : NumTypeBits;
1781
1782 /// An AttributedType::Kind
1783 unsigned AttrKind : 32 - NumTypeBits;
1784 };
1785
1787 friend class AutoType;
1788
1789 unsigned : NumTypeBits;
1790
1791 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1792 /// or '__auto_type'? AutoTypeKeyword value.
1793 unsigned Keyword : 2;
1794
1795 /// The number of template arguments in the type-constraints, which is
1796 /// expected to be able to hold at least 1024 according to [implimits].
1797 /// However as this limit is somewhat easy to hit with template
1798 /// metaprogramming we'd prefer to keep it as large as possible.
1799 /// At the moment it has been left as a non-bitfield since this type
1800 /// safely fits in 64 bits as an unsigned, so there is no reason to
1801 /// introduce the performance impact of a bitfield.
1802 unsigned NumArgs;
1803 };
1804
1806 friend class TypeOfType;
1807 friend class TypeOfExprType;
1808
1809 unsigned : NumTypeBits;
1810 unsigned IsUnqual : 1; // If true: typeof_unqual, else: typeof
1811 };
1812
1814 friend class UsingType;
1815
1816 unsigned : NumTypeBits;
1817
1818 /// True if the underlying type is different from the declared one.
1819 unsigned hasTypeDifferentFromDecl : 1;
1820 };
1821
1823 friend class TypedefType;
1824
1825 unsigned : NumTypeBits;
1826
1827 /// True if the underlying type is different from the declared one.
1828 unsigned hasTypeDifferentFromDecl : 1;
1829 };
1830
1833
1834 unsigned : NumTypeBits;
1835
1836 unsigned HasNonCanonicalUnderlyingType : 1;
1837
1838 // The index of the template parameter this substitution represents.
1839 unsigned Index : 15;
1840
1841 /// Represents the index within a pack if this represents a substitution
1842 /// from a pack expansion. This index starts at the end of the pack and
1843 /// increments towards the beginning.
1844 /// Positive non-zero number represents the index + 1.
1845 /// Zero means this is not substituted from an expansion.
1846 unsigned PackIndex : 16;
1847 };
1848
1851
1852 unsigned : NumTypeBits;
1853
1854 // The index of the template parameter this substitution represents.
1855 unsigned Index : 16;
1856
1857 /// The number of template arguments in \c Arguments, which is
1858 /// expected to be able to hold at least 1024 according to [implimits].
1859 /// However as this limit is somewhat easy to hit with template
1860 /// metaprogramming we'd prefer to keep it as large as possible.
1861 unsigned NumArgs : 16;
1862 };
1863
1866
1867 unsigned : NumTypeBits;
1868
1869 /// Whether this template specialization type is a substituted type alias.
1870 unsigned TypeAlias : 1;
1871
1872 /// The number of template arguments named in this class template
1873 /// specialization, which is expected to be able to hold at least 1024
1874 /// according to [implimits]. However, as this limit is somewhat easy to
1875 /// hit with template metaprogramming we'd prefer to keep it as large
1876 /// as possible. At the moment it has been left as a non-bitfield since
1877 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1878 /// to introduce the performance impact of a bitfield.
1879 unsigned NumArgs;
1880 };
1881
1884
1885 unsigned : NumTypeBits;
1887
1888 /// The number of template arguments named in this class template
1889 /// specialization, which is expected to be able to hold at least 1024
1890 /// according to [implimits]. However, as this limit is somewhat easy to
1891 /// hit with template metaprogramming we'd prefer to keep it as large
1892 /// as possible. At the moment it has been left as a non-bitfield since
1893 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1894 /// to introduce the performance impact of a bitfield.
1895 unsigned NumArgs;
1896 };
1897
1899 friend class PackExpansionType;
1900
1901 unsigned : NumTypeBits;
1902
1903 /// The number of expansions that this pack expansion will
1904 /// generate when substituted (+1), which is expected to be able to
1905 /// hold at least 1024 according to [implimits]. However, as this limit
1906 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1907 /// keep it as large as possible. At the moment it has been left as a
1908 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1909 /// there is no reason to introduce the performance impact of a bitfield.
1910 ///
1911 /// This field will only have a non-zero value when some of the parameter
1912 /// packs that occur within the pattern have been substituted but others
1913 /// have not.
1914 unsigned NumExpansions;
1915 };
1916
1917 union {
1918 TypeBitfields TypeBits;
1939 };
1940
1941private:
1942 template <class T> friend class TypePropertyCache;
1943
1944 /// Set whether this type comes from an AST file.
1945 void setFromAST(bool V = true) const {
1946 TypeBits.FromAST = V;
1947 }
1948
1949protected:
1950 friend class ASTContext;
1951
1954 canon.isNull() ? QualType(this_(), 0) : canon) {
1955 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1956 "changing bitfields changed sizeof(Type)!");
1957 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1958 "Insufficient alignment!");
1959 TypeBits.TC = tc;
1960 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1961 TypeBits.CacheValid = false;
1962 TypeBits.CachedLocalOrUnnamed = false;
1963 TypeBits.CachedLinkage = NoLinkage;
1964 TypeBits.FromAST = false;
1965 }
1966
1967 // silence VC++ warning C4355: 'this' : used in base member initializer list
1968 Type *this_() { return this; }
1969
1971 TypeBits.Dependence = static_cast<unsigned>(D);
1972 }
1973
1975
1976public:
1977 friend class ASTReader;
1978 friend class ASTWriter;
1979 template <class T> friend class serialization::AbstractTypeReader;
1980 template <class T> friend class serialization::AbstractTypeWriter;
1981
1982 Type(const Type &) = delete;
1983 Type(Type &&) = delete;
1984 Type &operator=(const Type &) = delete;
1985 Type &operator=(Type &&) = delete;
1986
1987 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1988
1989 /// Whether this type comes from an AST file.
1990 bool isFromAST() const { return TypeBits.FromAST; }
1991
1992 /// Whether this type is or contains an unexpanded parameter
1993 /// pack, used to support C++0x variadic templates.
1994 ///
1995 /// A type that contains a parameter pack shall be expanded by the
1996 /// ellipsis operator at some point. For example, the typedef in the
1997 /// following example contains an unexpanded parameter pack 'T':
1998 ///
1999 /// \code
2000 /// template<typename ...T>
2001 /// struct X {
2002 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
2003 /// };
2004 /// \endcode
2005 ///
2006 /// Note that this routine does not specify which
2008 return getDependence() & TypeDependence::UnexpandedPack;
2009 }
2010
2011 /// Determines if this type would be canonical if it had no further
2012 /// qualification.
2014 return CanonicalType == QualType(this, 0);
2015 }
2016
2017 /// Pull a single level of sugar off of this locally-unqualified type.
2018 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
2019 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
2021
2022 /// As an extension, we classify types as one of "sized" or "sizeless";
2023 /// every type is one or the other. Standard types are all sized;
2024 /// sizeless types are purely an extension.
2025 ///
2026 /// Sizeless types contain data with no specified size, alignment,
2027 /// or layout.
2028 bool isSizelessType() const;
2029 bool isSizelessBuiltinType() const;
2030
2031 /// Returns true for SVE scalable vector types.
2032 bool isSVESizelessBuiltinType() const;
2033
2034 /// Returns true for RVV scalable vector types.
2035 bool isRVVSizelessBuiltinType() const;
2036
2037 /// Check if this is a WebAssembly Reference Type.
2038 bool isWebAssemblyReferenceType() const;
2039 bool isWebAssemblyExternrefType() const;
2040
2041 /// Determines if this is a sizeless type supported by the
2042 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
2043 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
2044 bool isVLSTBuiltinType() const;
2045
2046 /// Returns the representative type for the element of an SVE builtin type.
2047 /// This is used to represent fixed-length SVE vectors created with the
2048 /// 'arm_sve_vector_bits' type attribute as VectorType.
2049 QualType getSveEltType(const ASTContext &Ctx) const;
2050
2051 /// Determines if this is a sizeless type supported by the
2052 /// 'riscv_rvv_vector_bits' type attribute, which can be applied to a single
2053 /// RVV vector or mask.
2054 bool isRVVVLSBuiltinType() const;
2055
2056 /// Returns the representative type for the element of an RVV builtin type.
2057 /// This is used to represent fixed-length RVV vectors created with the
2058 /// 'riscv_rvv_vector_bits' type attribute as VectorType.
2059 QualType getRVVEltType(const ASTContext &Ctx) const;
2060
2061 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
2062 /// object types, function types, and incomplete types.
2063
2064 /// Return true if this is an incomplete type.
2065 /// A type that can describe objects, but which lacks information needed to
2066 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
2067 /// routine will need to determine if the size is actually required.
2068 ///
2069 /// Def If non-null, and the type refers to some kind of declaration
2070 /// that can be completed (such as a C struct, C++ class, or Objective-C
2071 /// class), will be set to the declaration.
2072 bool isIncompleteType(NamedDecl **Def = nullptr) const;
2073
2074 /// Return true if this is an incomplete or object
2075 /// type, in other words, not a function type.
2077 return !isFunctionType();
2078 }
2079
2080 /// Determine whether this type is an object type.
2081 bool isObjectType() const {
2082 // C++ [basic.types]p8:
2083 // An object type is a (possibly cv-qualified) type that is not a
2084 // function type, not a reference type, and not a void type.
2085 return !isReferenceType() && !isFunctionType() && !isVoidType();
2086 }
2087
2088 /// Return true if this is a literal type
2089 /// (C++11 [basic.types]p10)
2090 bool isLiteralType(const ASTContext &Ctx) const;
2091
2092 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
2093 bool isStructuralType() const;
2094
2095 /// Test if this type is a standard-layout type.
2096 /// (C++0x [basic.type]p9)
2097 bool isStandardLayoutType() const;
2098
2099 /// Helper methods to distinguish type categories. All type predicates
2100 /// operate on the canonical type, ignoring typedefs and qualifiers.
2101
2102 /// Returns true if the type is a builtin type.
2103 bool isBuiltinType() const;
2104
2105 /// Test for a particular builtin type.
2106 bool isSpecificBuiltinType(unsigned K) const;
2107
2108 /// Test for a type which does not represent an actual type-system type but
2109 /// is instead used as a placeholder for various convenient purposes within
2110 /// Clang. All such types are BuiltinTypes.
2111 bool isPlaceholderType() const;
2112 const BuiltinType *getAsPlaceholderType() const;
2113
2114 /// Test for a specific placeholder type.
2115 bool isSpecificPlaceholderType(unsigned K) const;
2116
2117 /// Test for a placeholder type other than Overload; see
2118 /// BuiltinType::isNonOverloadPlaceholderType.
2119 bool isNonOverloadPlaceholderType() const;
2120
2121 /// isIntegerType() does *not* include complex integers (a GCC extension).
2122 /// isComplexIntegerType() can be used to test for complex integers.
2123 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
2124 bool isEnumeralType() const;
2125
2126 /// Determine whether this type is a scoped enumeration type.
2127 bool isScopedEnumeralType() const;
2128 bool isBooleanType() const;
2129 bool isCharType() const;
2130 bool isWideCharType() const;
2131 bool isChar8Type() const;
2132 bool isChar16Type() const;
2133 bool isChar32Type() const;
2134 bool isAnyCharacterType() const;
2135 bool isIntegralType(const ASTContext &Ctx) const;
2136
2137 /// Determine whether this type is an integral or enumeration type.
2138 bool isIntegralOrEnumerationType() const;
2139
2140 /// Determine whether this type is an integral or unscoped enumeration type.
2142 bool isUnscopedEnumerationType() const;
2143
2144 /// Floating point categories.
2145 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2146 /// isComplexType() does *not* include complex integers (a GCC extension).
2147 /// isComplexIntegerType() can be used to test for complex integers.
2148 bool isComplexType() const; // C99 6.2.5p11 (complex)
2149 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2150 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2151 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2152 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2153 bool isBFloat16Type() const;
2154 bool isFloat128Type() const;
2155 bool isIbm128Type() const;
2156 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2157 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2158 bool isVoidType() const; // C99 6.2.5p19
2159 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2160 bool isAggregateType() const;
2161 bool isFundamentalType() const;
2162 bool isCompoundType() const;
2163
2164 // Type Predicates: Check to see if this type is structurally the specified
2165 // type, ignoring typedefs and qualifiers.
2166 bool isFunctionType() const;
2167 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2168 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2169 bool isPointerType() const;
2170 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2171 bool isBlockPointerType() const;
2172 bool isVoidPointerType() const;
2173 bool isReferenceType() const;
2174 bool isLValueReferenceType() const;
2175 bool isRValueReferenceType() const;
2176 bool isObjectPointerType() const;
2177 bool isFunctionPointerType() const;
2178 bool isFunctionReferenceType() const;
2179 bool isMemberPointerType() const;
2180 bool isMemberFunctionPointerType() const;
2181 bool isMemberDataPointerType() const;
2182 bool isArrayType() const;
2183 bool isConstantArrayType() const;
2184 bool isIncompleteArrayType() const;
2185 bool isVariableArrayType() const;
2186 bool isDependentSizedArrayType() const;
2187 bool isRecordType() const;
2188 bool isClassType() const;
2189 bool isStructureType() const;
2190 bool isObjCBoxableRecordType() const;
2191 bool isInterfaceType() const;
2192 bool isStructureOrClassType() const;
2193 bool isUnionType() const;
2194 bool isComplexIntegerType() const; // GCC _Complex integer type.
2195 bool isVectorType() const; // GCC vector type.
2196 bool isExtVectorType() const; // Extended vector type.
2197 bool isExtVectorBoolType() const; // Extended vector type with bool element.
2198 bool isMatrixType() const; // Matrix type.
2199 bool isConstantMatrixType() const; // Constant matrix type.
2200 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2201 bool isObjCObjectPointerType() const; // pointer to ObjC object
2202 bool isObjCRetainableType() const; // ObjC object or block pointer
2203 bool isObjCLifetimeType() const; // (array of)* retainable type
2204 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2205 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2206 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2207 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2208 // for the common case.
2209 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2210 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2211 bool isObjCQualifiedIdType() const; // id<foo>
2212 bool isObjCQualifiedClassType() const; // Class<foo>
2213 bool isObjCObjectOrInterfaceType() const;
2214 bool isObjCIdType() const; // id
2215 bool isDecltypeType() const;
2216 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2217 /// qualifier?
2218 ///
2219 /// This approximates the answer to the following question: if this
2220 /// translation unit were compiled in ARC, would this type be qualified
2221 /// with __unsafe_unretained?
2223 return hasAttr(attr::ObjCInertUnsafeUnretained);
2224 }
2225
2226 /// Whether the type is Objective-C 'id' or a __kindof type of an
2227 /// object type, e.g., __kindof NSView * or __kindof id
2228 /// <NSCopying>.
2229 ///
2230 /// \param bound Will be set to the bound on non-id subtype types,
2231 /// which will be (possibly specialized) Objective-C class type, or
2232 /// null for 'id.
2233 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2234 const ObjCObjectType *&bound) const;
2235
2236 bool isObjCClassType() const; // Class
2237
2238 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2239 /// Class type, e.g., __kindof Class <NSCopying>.
2240 ///
2241 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2242 /// here because Objective-C's type system cannot express "a class
2243 /// object for a subclass of NSFoo".
2244 bool isObjCClassOrClassKindOfType() const;
2245
2247 bool isObjCSelType() const; // Class
2248 bool isObjCBuiltinType() const; // 'id' or 'Class'
2249 bool isObjCARCBridgableType() const;
2250 bool isCARCBridgableType() const;
2251 bool isTemplateTypeParmType() const; // C++ template type parameter
2252 bool isNullPtrType() const; // C++11 std::nullptr_t or
2253 // C2x nullptr_t
2254 bool isNothrowT() const; // C++ std::nothrow_t
2255 bool isAlignValT() const; // C++17 std::align_val_t
2256 bool isStdByteType() const; // C++17 std::byte
2257 bool isAtomicType() const; // C11 _Atomic()
2258 bool isUndeducedAutoType() const; // C++11 auto or
2259 // C++14 decltype(auto)
2260 bool isTypedefNameType() const; // typedef or alias template
2261
2262#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2263 bool is##Id##Type() const;
2264#include "clang/Basic/OpenCLImageTypes.def"
2265
2266 bool isImageType() const; // Any OpenCL image type
2267
2268 bool isSamplerT() const; // OpenCL sampler_t
2269 bool isEventT() const; // OpenCL event_t
2270 bool isClkEventT() const; // OpenCL clk_event_t
2271 bool isQueueT() const; // OpenCL queue_t
2272 bool isReserveIDT() const; // OpenCL reserve_id_t
2273
2274#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2275 bool is##Id##Type() const;
2276#include "clang/Basic/OpenCLExtensionTypes.def"
2277 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2278 bool isOCLIntelSubgroupAVCType() const;
2279 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2280
2281 bool isPipeType() const; // OpenCL pipe type
2282 bool isBitIntType() const; // Bit-precise integer type
2283 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2284
2285 /// Determines if this type, which must satisfy
2286 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2287 /// than implicitly __strong.
2289
2290 /// Check if the type is the CUDA device builtin surface type.
2291 bool isCUDADeviceBuiltinSurfaceType() const;
2292 /// Check if the type is the CUDA device builtin texture type.
2293 bool isCUDADeviceBuiltinTextureType() const;
2294
2295 bool isRVVType() const;
2296
2297 bool isRVVType(unsigned Bitwidth, bool IsFloat) const;
2298
2299 /// Return the implicit lifetime for this type, which must not be dependent.
2301
2314
2315 /// Given that this is a scalar type, classify it.
2317
2319 return static_cast<TypeDependence>(TypeBits.Dependence);
2320 }
2321
2322 /// Whether this type is an error type.
2323 bool containsErrors() const {
2324 return getDependence() & TypeDependence::Error;
2325 }
2326
2327 /// Whether this type is a dependent type, meaning that its definition
2328 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2329 bool isDependentType() const {
2330 return getDependence() & TypeDependence::Dependent;
2331 }
2332
2333 /// Determine whether this type is an instantiation-dependent type,
2334 /// meaning that the type involves a template parameter (even if the
2335 /// definition does not actually depend on the type substituted for that
2336 /// template parameter).
2338 return getDependence() & TypeDependence::Instantiation;
2339 }
2340
2341 /// Determine whether this type is an undeduced type, meaning that
2342 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2343 /// deduced.
2344 bool isUndeducedType() const;
2345
2346 /// Whether this type is a variably-modified type (C99 6.7.5).
2348 return getDependence() & TypeDependence::VariablyModified;
2349 }
2350
2351 /// Whether this type involves a variable-length array type
2352 /// with a definite size.
2353 bool hasSizedVLAType() const;
2354
2355 /// Whether this type is or contains a local or unnamed type.
2356 bool hasUnnamedOrLocalType() const;
2357
2358 bool isOverloadableType() const;
2359
2360 /// Determine wither this type is a C++ elaborated-type-specifier.
2361 bool isElaboratedTypeSpecifier() const;
2362
2363 bool canDecayToPointerType() const;
2364
2365 /// Whether this type is represented natively as a pointer. This includes
2366 /// pointers, references, block pointers, and Objective-C interface,
2367 /// qualified id, and qualified interface types, as well as nullptr_t.
2368 bool hasPointerRepresentation() const;
2369
2370 /// Whether this type can represent an objective pointer type for the
2371 /// purpose of GC'ability
2372 bool hasObjCPointerRepresentation() const;
2373
2374 /// Determine whether this type has an integer representation
2375 /// of some sort, e.g., it is an integer type or a vector.
2376 bool hasIntegerRepresentation() const;
2377
2378 /// Determine whether this type has an signed integer representation
2379 /// of some sort, e.g., it is an signed integer type or a vector.
2380 bool hasSignedIntegerRepresentation() const;
2381
2382 /// Determine whether this type has an unsigned integer representation
2383 /// of some sort, e.g., it is an unsigned integer type or a vector.
2385
2386 /// Determine whether this type has a floating-point representation
2387 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2388 bool hasFloatingRepresentation() const;
2389
2390 // Type Checking Functions: Check to see if this type is structurally the
2391 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2392 // the best type we can.
2393 const RecordType *getAsStructureType() const;
2394 /// NOTE: getAs*ArrayType are methods on ASTContext.
2395 const RecordType *getAsUnionType() const;
2396 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2398
2399 // The following is a convenience method that returns an ObjCObjectPointerType
2400 // for object declared using an interface.
2405
2406 /// Retrieves the CXXRecordDecl that this type refers to, either
2407 /// because the type is a RecordType or because it is the injected-class-name
2408 /// type of a class template or class template partial specialization.
2410
2411 /// Retrieves the RecordDecl this type refers to.
2412 RecordDecl *getAsRecordDecl() const;
2413
2414 /// Retrieves the TagDecl that this type refers to, either
2415 /// because the type is a TagType or because it is the injected-class-name
2416 /// type of a class template or class template partial specialization.
2417 TagDecl *getAsTagDecl() const;
2418
2419 /// If this is a pointer or reference to a RecordType, return the
2420 /// CXXRecordDecl that the type refers to.
2421 ///
2422 /// If this is not a pointer or reference, or the type being pointed to does
2423 /// not refer to a CXXRecordDecl, returns NULL.
2425
2426 /// Get the DeducedType whose type will be deduced for a variable with
2427 /// an initializer of this type. This looks through declarators like pointer
2428 /// types, but not through decltype or typedefs.
2430
2431 /// Get the AutoType whose type will be deduced for a variable with
2432 /// an initializer of this type. This looks through declarators like pointer
2433 /// types, but not through decltype or typedefs.
2435 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2436 }
2437
2438 /// Determine whether this type was written with a leading 'auto'
2439 /// corresponding to a trailing return type (possibly for a nested
2440 /// function type within a pointer to function type or similar).
2441 bool hasAutoForTrailingReturnType() const;
2442
2443 /// Member-template getAs<specific type>'. Look through sugar for
2444 /// an instance of <specific type>. This scheme will eventually
2445 /// replace the specific getAsXXXX methods above.
2446 ///
2447 /// There are some specializations of this member template listed
2448 /// immediately following this class.
2449 template <typename T> const T *getAs() const;
2450
2451 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2452 /// of sugar (parens, attributes, etc) for an instance of <specific type>.
2453 /// This is used when you need to walk over sugar nodes that represent some
2454 /// kind of type adjustment from a type that was written as a <specific type>
2455 /// to another type that is still canonically a <specific type>.
2456 template <typename T> const T *getAsAdjusted() const;
2457
2458 /// A variant of getAs<> for array types which silently discards
2459 /// qualifiers from the outermost type.
2460 const ArrayType *getAsArrayTypeUnsafe() const;
2461
2462 /// Member-template castAs<specific type>. Look through sugar for
2463 /// the underlying instance of <specific type>.
2464 ///
2465 /// This method has the same relationship to getAs<T> as cast<T> has
2466 /// to dyn_cast<T>; which is to say, the underlying type *must*
2467 /// have the intended type, and this method will never return null.
2468 template <typename T> const T *castAs() const;
2469
2470 /// A variant of castAs<> for array type which silently discards
2471 /// qualifiers from the outermost type.
2472 const ArrayType *castAsArrayTypeUnsafe() const;
2473
2474 /// Determine whether this type had the specified attribute applied to it
2475 /// (looking through top-level type sugar).
2476 bool hasAttr(attr::Kind AK) const;
2477
2478 /// Get the base element type of this type, potentially discarding type
2479 /// qualifiers. This should never be used when type qualifiers
2480 /// are meaningful.
2481 const Type *getBaseElementTypeUnsafe() const;
2482
2483 /// If this is an array type, return the element type of the array,
2484 /// potentially with type qualifiers missing.
2485 /// This should never be used when type qualifiers are meaningful.
2486 const Type *getArrayElementTypeNoTypeQual() const;
2487
2488 /// If this is a pointer type, return the pointee type.
2489 /// If this is an array type, return the array element type.
2490 /// This should never be used when type qualifiers are meaningful.
2491 const Type *getPointeeOrArrayElementType() const;
2492
2493 /// If this is a pointer, ObjC object pointer, or block
2494 /// pointer, this returns the respective pointee.
2495 QualType getPointeeType() const;
2496
2497 /// Return the specified type with any "sugar" removed from the type,
2498 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2499 const Type *getUnqualifiedDesugaredType() const;
2500
2501 /// Return true if this is an integer type that is
2502 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2503 /// or an enum decl which has a signed representation.
2504 bool isSignedIntegerType() const;
2505
2506 /// Return true if this is an integer type that is
2507 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2508 /// or an enum decl which has an unsigned representation.
2509 bool isUnsignedIntegerType() const;
2510
2511 /// Determines whether this is an integer type that is signed or an
2512 /// enumeration types whose underlying type is a signed integer type.
2514
2515 /// Determines whether this is an integer type that is unsigned or an
2516 /// enumeration types whose underlying type is a unsigned integer type.
2518
2519 /// Return true if this is a fixed point type according to
2520 /// ISO/IEC JTC1 SC22 WG14 N1169.
2521 bool isFixedPointType() const;
2522
2523 /// Return true if this is a fixed point or integer type.
2524 bool isFixedPointOrIntegerType() const;
2525
2526 /// Return true if this is a saturated fixed point type according to
2527 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2528 bool isSaturatedFixedPointType() const;
2529
2530 /// Return true if this is a saturated fixed point type according to
2531 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2532 bool isUnsaturatedFixedPointType() const;
2533
2534 /// Return true if this is a fixed point type that is signed according
2535 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2536 bool isSignedFixedPointType() const;
2537
2538 /// Return true if this is a fixed point type that is unsigned according
2539 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2540 bool isUnsignedFixedPointType() const;
2541
2542 /// Return true if this is not a variable sized type,
2543 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2544 /// incomplete types.
2545 bool isConstantSizeType() const;
2546
2547 /// Returns true if this type can be represented by some
2548 /// set of type specifiers.
2549 bool isSpecifierType() const;
2550
2551 /// Determine the linkage of this type.
2552 Linkage getLinkage() const;
2553
2554 /// Determine the visibility of this type.
2557 }
2558
2559 /// Return true if the visibility was explicitly set is the code.
2562 }
2563
2564 /// Determine the linkage and visibility of this type.
2566
2567 /// True if the computed linkage is valid. Used for consistency
2568 /// checking. Should always return true.
2569 bool isLinkageValid() const;
2570
2571 /// Determine the nullability of the given type.
2572 ///
2573 /// Note that nullability is only captured as sugar within the type
2574 /// system, not as part of the canonical type, so nullability will
2575 /// be lost by canonicalization and desugaring.
2576 std::optional<NullabilityKind> getNullability() const;
2577
2578 /// Determine whether the given type can have a nullability
2579 /// specifier applied to it, i.e., if it is any kind of pointer type.
2580 ///
2581 /// \param ResultIfUnknown The value to return if we don't yet know whether
2582 /// this type can have nullability because it is dependent.
2583 bool canHaveNullability(bool ResultIfUnknown = true) const;
2584
2585 /// Retrieve the set of substitutions required when accessing a member
2586 /// of the Objective-C receiver type that is declared in the given context.
2587 ///
2588 /// \c *this is the type of the object we're operating on, e.g., the
2589 /// receiver for a message send or the base of a property access, and is
2590 /// expected to be of some object or object pointer type.
2591 ///
2592 /// \param dc The declaration context for which we are building up a
2593 /// substitution mapping, which should be an Objective-C class, extension,
2594 /// category, or method within.
2595 ///
2596 /// \returns an array of type arguments that can be substituted for
2597 /// the type parameters of the given declaration context in any type described
2598 /// within that context, or an empty optional to indicate that no
2599 /// substitution is required.
2600 std::optional<ArrayRef<QualType>>
2601 getObjCSubstitutions(const DeclContext *dc) const;
2602
2603 /// Determines if this is an ObjC interface type that may accept type
2604 /// parameters.
2605 bool acceptsObjCTypeParams() const;
2606
2607 const char *getTypeClassName() const;
2608
2610 return CanonicalType;
2611 }
2612
2613 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2614 void dump() const;
2615 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2616};
2617
2618/// This will check for a TypedefType by removing any existing sugar
2619/// until it reaches a TypedefType or a non-sugared type.
2620template <> const TypedefType *Type::getAs() const;
2621template <> const UsingType *Type::getAs() const;
2622
2623/// This will check for a TemplateSpecializationType by removing any
2624/// existing sugar until it reaches a TemplateSpecializationType or a
2625/// non-sugared type.
2626template <> const TemplateSpecializationType *Type::getAs() const;
2627
2628/// This will check for an AttributedType by removing any existing sugar
2629/// until it reaches an AttributedType or a non-sugared type.
2630template <> const AttributedType *Type::getAs() const;
2631
2632// We can do canonical leaf types faster, because we don't have to
2633// worry about preserving child type decoration.
2634#define TYPE(Class, Base)
2635#define LEAF_TYPE(Class) \
2636template <> inline const Class##Type *Type::getAs() const { \
2637 return dyn_cast<Class##Type>(CanonicalType); \
2638} \
2639template <> inline const Class##Type *Type::castAs() const { \
2640 return cast<Class##Type>(CanonicalType); \
2641}
2642#include "clang/AST/TypeNodes.inc"
2643
2644/// This class is used for builtin types like 'int'. Builtin
2645/// types are always canonical and have a literal name field.
2646class BuiltinType : public Type {
2647public:
2648 enum Kind {
2649// OpenCL image types
2650#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2651#include "clang/Basic/OpenCLImageTypes.def"
2652// OpenCL extension types
2653#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2654#include "clang/Basic/OpenCLExtensionTypes.def"
2655// SVE Types
2656#define SVE_TYPE(Name, Id, SingletonId) Id,
2657#include "clang/Basic/AArch64SVEACLETypes.def"
2658// PPC MMA Types
2659#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2660#include "clang/Basic/PPCTypes.def"
2661// RVV Types
2662#define RVV_TYPE(Name, Id, SingletonId) Id,
2663#include "clang/Basic/RISCVVTypes.def"
2664// WebAssembly reference types
2665#define WASM_TYPE(Name, Id, SingletonId) Id,
2666#include "clang/Basic/WebAssemblyReferenceTypes.def"
2667// All other builtin types
2668#define BUILTIN_TYPE(Id, SingletonId) Id,
2669#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2670#include "clang/AST/BuiltinTypes.def"
2671 };
2672
2673private:
2674 friend class ASTContext; // ASTContext creates these.
2675
2676 BuiltinType(Kind K)
2677 : Type(Builtin, QualType(),
2678 K == Dependent ? TypeDependence::DependentInstantiation
2679 : TypeDependence::None) {
2680 BuiltinTypeBits.Kind = K;
2681 }
2682
2683public:
2684 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2685 StringRef getName(const PrintingPolicy &Policy) const;
2686
2687 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2688 // The StringRef is null-terminated.
2689 StringRef str = getName(Policy);
2690 assert(!str.empty() && str.data()[str.size()] == '\0');
2691 return str.data();
2692 }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 bool isInteger() const {
2698 return getKind() >= Bool && getKind() <= Int128;
2699 }
2700
2701 bool isSignedInteger() const {
2702 return getKind() >= Char_S && getKind() <= Int128;
2703 }
2704
2705 bool isUnsignedInteger() const {
2706 return getKind() >= Bool && getKind() <= UInt128;
2707 }
2708
2709 bool isFloatingPoint() const {
2710 return getKind() >= Half && getKind() <= Ibm128;
2711 }
2712
2713 bool isSVEBool() const { return getKind() == Kind::SveBool; }
2714
2715 bool isSVECount() const { return getKind() == Kind::SveCount; }
2716
2717 /// Determines whether the given kind corresponds to a placeholder type.
2719 return K >= Overload;
2720 }
2721
2722 /// Determines whether this type is a placeholder type, i.e. a type
2723 /// which cannot appear in arbitrary positions in a fully-formed
2724 /// expression.
2725 bool isPlaceholderType() const {
2727 }
2728
2729 /// Determines whether this type is a placeholder type other than
2730 /// Overload. Most placeholder types require only syntactic
2731 /// information about their context in order to be resolved (e.g.
2732 /// whether it is a call expression), which means they can (and
2733 /// should) be resolved in an earlier "phase" of analysis.
2734 /// Overload expressions sometimes pick up further information
2735 /// from their context, like whether the context expects a
2736 /// specific function-pointer type, and so frequently need
2737 /// special treatment.
2739 return getKind() > Overload;
2740 }
2741
2742 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2743};
2744
2745/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2746/// types (_Complex float etc) as well as the GCC integer complex extensions.
2747class ComplexType : public Type, public llvm::FoldingSetNode {
2748 friend class ASTContext; // ASTContext creates these.
2749
2750 QualType ElementType;
2751
2752 ComplexType(QualType Element, QualType CanonicalPtr)
2753 : Type(Complex, CanonicalPtr, Element->getDependence()),
2754 ElementType(Element) {}
2755
2756public:
2757 QualType getElementType() const { return ElementType; }
2758
2759 bool isSugared() const { return false; }
2760 QualType desugar() const { return QualType(this, 0); }
2761
2762 void Profile(llvm::FoldingSetNodeID &ID) {
2763 Profile(ID, getElementType());
2764 }
2765
2766 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2767 ID.AddPointer(Element.getAsOpaquePtr());
2768 }
2769
2770 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2771};
2772
2773/// Sugar for parentheses used when specifying types.
2774class ParenType : public Type, public llvm::FoldingSetNode {
2775 friend class ASTContext; // ASTContext creates these.
2776
2777 QualType Inner;
2778
2779 ParenType(QualType InnerType, QualType CanonType)
2780 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2781
2782public:
2783 QualType getInnerType() const { return Inner; }
2784
2785 bool isSugared() const { return true; }
2786 QualType desugar() const { return getInnerType(); }
2787
2788 void Profile(llvm::FoldingSetNodeID &ID) {
2789 Profile(ID, getInnerType());
2790 }
2791
2792 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2793 Inner.Profile(ID);
2794 }
2795
2796 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2797};
2798
2799/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2800class PointerType : public Type, public llvm::FoldingSetNode {
2801 friend class ASTContext; // ASTContext creates these.
2802
2803 QualType PointeeType;
2804
2805 PointerType(QualType Pointee, QualType CanonicalPtr)
2806 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2807 PointeeType(Pointee) {}
2808
2809public:
2810 QualType getPointeeType() const { return PointeeType; }
2811
2812 bool isSugared() const { return false; }
2813 QualType desugar() const { return QualType(this, 0); }
2814
2815 void Profile(llvm::FoldingSetNodeID &ID) {
2816 Profile(ID, getPointeeType());
2817 }
2818
2819 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2820 ID.AddPointer(Pointee.getAsOpaquePtr());
2821 }
2822
2823 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2824};
2825
2826/// Represents a type which was implicitly adjusted by the semantic
2827/// engine for arbitrary reasons. For example, array and function types can
2828/// decay, and function types can have their calling conventions adjusted.
2829class AdjustedType : public Type, public llvm::FoldingSetNode {
2830 QualType OriginalTy;
2831 QualType AdjustedTy;
2832
2833protected:
2834 friend class ASTContext; // ASTContext creates these.
2835
2836 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2837 QualType CanonicalPtr)
2838 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2839 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2840
2841public:
2842 QualType getOriginalType() const { return OriginalTy; }
2843 QualType getAdjustedType() const { return AdjustedTy; }
2844
2845 bool isSugared() const { return true; }
2846 QualType desugar() const { return AdjustedTy; }
2847
2848 void Profile(llvm::FoldingSetNodeID &ID) {
2849 Profile(ID, OriginalTy, AdjustedTy);
2850 }
2851
2852 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2853 ID.AddPointer(Orig.getAsOpaquePtr());
2854 ID.AddPointer(New.getAsOpaquePtr());
2855 }
2856
2857 static bool classof(const Type *T) {
2858 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2859 }
2860};
2861
2862/// Represents a pointer type decayed from an array or function type.
2864 friend class ASTContext; // ASTContext creates these.
2865
2866 inline
2867 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2868
2869public:
2871
2872 inline QualType getPointeeType() const;
2873
2874 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2875};
2876
2877/// Pointer to a block type.
2878/// This type is to represent types syntactically represented as
2879/// "void (^)(int)", etc. Pointee is required to always be a function type.
2880class BlockPointerType : public Type, public llvm::FoldingSetNode {
2881 friend class ASTContext; // ASTContext creates these.
2882
2883 // Block is some kind of pointer type
2884 QualType PointeeType;
2885
2886 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2887 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2888 PointeeType(Pointee) {}
2889
2890public:
2891 // Get the pointee type. Pointee is required to always be a function type.
2892 QualType getPointeeType() const { return PointeeType; }
2893
2894 bool isSugared() const { return false; }
2895 QualType desugar() const { return QualType(this, 0); }
2896
2897 void Profile(llvm::FoldingSetNodeID &ID) {
2898 Profile(ID, getPointeeType());
2899 }
2900
2901 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2902 ID.AddPointer(Pointee.getAsOpaquePtr());
2903 }
2904
2905 static bool classof(const Type *T) {
2906 return T->getTypeClass() == BlockPointer;
2907 }
2908};
2909
2910/// Base for LValueReferenceType and RValueReferenceType
2911class ReferenceType : public Type, public llvm::FoldingSetNode {
2912 QualType PointeeType;
2913
2914protected:
2915 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2916 bool SpelledAsLValue)
2917 : Type(tc, CanonicalRef, Referencee->getDependence()),
2918 PointeeType(Referencee) {
2919 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2920 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2921 }
2922
2923public:
2924 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2925 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2926
2927 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2928
2930 // FIXME: this might strip inner qualifiers; okay?
2931 const ReferenceType *T = this;
2932 while (T->isInnerRef())
2933 T = T->PointeeType->castAs<ReferenceType>();
2934 return T->PointeeType;
2935 }
2936
2937 void Profile(llvm::FoldingSetNodeID &ID) {
2938 Profile(ID, PointeeType, isSpelledAsLValue());
2939 }
2940
2941 static void Profile(llvm::FoldingSetNodeID &ID,
2942 QualType Referencee,
2943 bool SpelledAsLValue) {
2944 ID.AddPointer(Referencee.getAsOpaquePtr());
2945 ID.AddBoolean(SpelledAsLValue);
2946 }
2947
2948 static bool classof(const Type *T) {
2949 return T->getTypeClass() == LValueReference ||
2950 T->getTypeClass() == RValueReference;
2951 }
2952};
2953
2954/// An lvalue reference type, per C++11 [dcl.ref].
2956 friend class ASTContext; // ASTContext creates these
2957
2958 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2959 bool SpelledAsLValue)
2960 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2961 SpelledAsLValue) {}
2962
2963public:
2964 bool isSugared() const { return false; }
2965 QualType desugar() const { return QualType(this, 0); }
2966
2967 static bool classof(const Type *T) {
2968 return T->getTypeClass() == LValueReference;
2969 }
2970};
2971
2972/// An rvalue reference type, per C++11 [dcl.ref].
2974 friend class ASTContext; // ASTContext creates these
2975
2976 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2977 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2978
2979public:
2980 bool isSugared() const { return false; }
2981 QualType desugar() const { return QualType(this, 0); }
2982
2983 static bool classof(const Type *T) {
2984 return T->getTypeClass() == RValueReference;
2985 }
2986};
2987
2988/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2989///
2990/// This includes both pointers to data members and pointer to member functions.
2991class MemberPointerType : public Type, public llvm::FoldingSetNode {
2992 friend class ASTContext; // ASTContext creates these.
2993
2994 QualType PointeeType;
2995
2996 /// The class of which the pointee is a member. Must ultimately be a
2997 /// RecordType, but could be a typedef or a template parameter too.
2998 const Type *Class;
2999
3000 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
3001 : Type(MemberPointer, CanonicalPtr,
3002 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
3003 Pointee->getDependence()),
3004 PointeeType(Pointee), Class(Cls) {}
3005
3006public:
3007 QualType getPointeeType() const { return PointeeType; }
3008
3009 /// Returns true if the member type (i.e. the pointee type) is a
3010 /// function type rather than a data-member type.
3012 return PointeeType->isFunctionProtoType();
3013 }
3014
3015 /// Returns true if the member type (i.e. the pointee type) is a
3016 /// data type rather than a function type.
3017 bool isMemberDataPointer() const {
3018 return !PointeeType->isFunctionProtoType();
3019 }
3020
3021 const Type *getClass() const { return Class; }
3023
3024 bool isSugared() const { return false; }
3025 QualType desugar() const { return QualType(this, 0); }
3026
3027 void Profile(llvm::FoldingSetNodeID &ID) {
3029 }
3030
3031 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
3032 const Type *Class) {
3033 ID.AddPointer(Pointee.getAsOpaquePtr());
3034 ID.AddPointer(Class);
3035 }
3036
3037 static bool classof(const Type *T) {
3038 return T->getTypeClass() == MemberPointer;
3039 }
3040};
3041
3042/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
3043class ArrayType : public Type, public llvm::FoldingSetNode {
3044public:
3045 /// Capture whether this is a normal array (e.g. int X[4])
3046 /// an array with a static size (e.g. int X[static 4]), or an array
3047 /// with a star size (e.g. int X[*]).
3048 /// 'static' is only allowed on function parameters.
3052
3053private:
3054 /// The element type of the array.
3055 QualType ElementType;
3056
3057protected:
3058 friend class ASTContext; // ASTContext creates these.
3059
3061 unsigned tq, const Expr *sz = nullptr);
3062
3063public:
3064 QualType getElementType() const { return ElementType; }
3065
3067 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
3068 }
3069
3072 }
3073
3074 unsigned getIndexTypeCVRQualifiers() const {
3075 return ArrayTypeBits.IndexTypeQuals;
3076 }
3077
3078 static bool classof(const Type *T) {
3079 return T->getTypeClass() == ConstantArray ||
3080 T->getTypeClass() == VariableArray ||
3081 T->getTypeClass() == IncompleteArray ||
3082 T->getTypeClass() == DependentSizedArray;
3083 }
3084};
3085
3086/// Represents the canonical version of C arrays with a specified constant size.
3087/// For example, the canonical type for 'int A[4 + 4*100]' is a
3088/// ConstantArrayType where the element type is 'int' and the size is 404.
3090 : public ArrayType,
3091 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
3092 friend class ASTContext; // ASTContext creates these.
3093 friend TrailingObjects;
3094
3095 llvm::APInt Size; // Allows us to unique the type.
3096
3097 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
3098 const Expr *sz, ArraySizeModifier sm, unsigned tq)
3099 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
3100 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
3101 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
3102 assert(!can.isNull() && "canonical constant array should not have size");
3103 *getTrailingObjects<const Expr*>() = sz;
3104 }
3105 }
3106
3107 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
3108 return ConstantArrayTypeBits.HasStoredSizeExpr;
3109 }
3110
3111public:
3112 const llvm::APInt &getSize() const { return Size; }
3113 const Expr *getSizeExpr() const {
3114 return ConstantArrayTypeBits.HasStoredSizeExpr
3115 ? *getTrailingObjects<const Expr *>()
3116 : nullptr;
3117 }
3118 bool isSugared() const { return false; }
3119 QualType desugar() const { return QualType(this, 0); }
3120
3121 /// Determine the number of bits required to address a member of
3122 // an array with the given element type and number of elements.
3123 static unsigned getNumAddressingBits(const ASTContext &Context,
3124 QualType ElementType,
3125 const llvm::APInt &NumElements);
3126
3127 /// Determine the maximum number of active bits that an array's size
3128 /// can require, which limits the maximum size of the array.
3129 static unsigned getMaxSizeBits(const ASTContext &Context);
3130
3131 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3132 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
3134 }
3135
3136 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
3137 QualType ET, const llvm::APInt &ArraySize,
3138 const Expr *SizeExpr, ArraySizeModifier SizeMod,
3139 unsigned TypeQuals);
3140
3141 static bool classof(const Type *T) {
3142 return T->getTypeClass() == ConstantArray;
3143 }
3144};
3145
3146/// Represents a C array with an unspecified size. For example 'int A[]' has
3147/// an IncompleteArrayType where the element type is 'int' and the size is
3148/// unspecified.
3150 friend class ASTContext; // ASTContext creates these.
3151
3153 ArraySizeModifier sm, unsigned tq)
3154 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3155
3156public:
3157 friend class StmtIteratorBase;
3158
3159 bool isSugared() const { return false; }
3160 QualType desugar() const { return QualType(this, 0); }
3161
3162 static bool classof(const Type *T) {
3163 return T->getTypeClass() == IncompleteArray;
3164 }
3165
3166 void Profile(llvm::FoldingSetNodeID &ID) {
3169 }
3170
3171 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3172 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3173 ID.AddPointer(ET.getAsOpaquePtr());
3174 ID.AddInteger(SizeMod);
3175 ID.AddInteger(TypeQuals);
3176 }
3177};
3178
3179/// Represents a C array with a specified size that is not an
3180/// integer-constant-expression. For example, 'int s[x+foo()]'.
3181/// Since the size expression is an arbitrary expression, we store it as such.
3182///
3183/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3184/// should not be: two lexically equivalent variable array types could mean
3185/// different things, for example, these variables do not have the same type
3186/// dynamically:
3187///
3188/// void foo(int x) {
3189/// int Y[x];
3190/// ++x;
3191/// int Z[x];
3192/// }
3194 friend class ASTContext; // ASTContext creates these.
3195
3196 /// An assignment-expression. VLA's are only permitted within
3197 /// a function block.
3198 Stmt *SizeExpr;
3199
3200 /// The range spanned by the left and right array brackets.
3201 SourceRange Brackets;
3202
3204 ArraySizeModifier sm, unsigned tq,
3205 SourceRange brackets)
3206 : ArrayType(VariableArray, et, can, sm, tq, e),
3207 SizeExpr((Stmt*) e), Brackets(brackets) {}
3208
3209public:
3210 friend class StmtIteratorBase;
3211
3213 // We use C-style casts instead of cast<> here because we do not wish
3214 // to have a dependency of Type.h on Stmt.h/Expr.h.
3215 return (Expr*) SizeExpr;
3216 }
3217
3218 SourceRange getBracketsRange() const { return Brackets; }
3219 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3220 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3221
3222 bool isSugared() const { return false; }
3223 QualType desugar() const { return QualType(this, 0); }
3224
3225 static bool classof(const Type *T) {
3226 return T->getTypeClass() == VariableArray;
3227 }
3228
3229 void Profile(llvm::FoldingSetNodeID &ID) {
3230 llvm_unreachable("Cannot unique VariableArrayTypes.");
3231 }
3232};
3233
3234/// Represents an array type in C++ whose size is a value-dependent expression.
3235///
3236/// For example:
3237/// \code
3238/// template<typename T, int Size>
3239/// class array {
3240/// T data[Size];
3241/// };
3242/// \endcode
3243///
3244/// For these types, we won't actually know what the array bound is
3245/// until template instantiation occurs, at which point this will
3246/// become either a ConstantArrayType or a VariableArrayType.
3248 friend class ASTContext; // ASTContext creates these.
3249
3250 const ASTContext &Context;
3251
3252 /// An assignment expression that will instantiate to the
3253 /// size of the array.
3254 ///
3255 /// The expression itself might be null, in which case the array
3256 /// type will have its size deduced from an initializer.
3257 Stmt *SizeExpr;
3258
3259 /// The range spanned by the left and right array brackets.
3260 SourceRange Brackets;
3261
3262 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3263 Expr *e, ArraySizeModifier sm, unsigned tq,
3264 SourceRange brackets);
3265
3266public:
3267 friend class StmtIteratorBase;
3268
3270 // We use C-style casts instead of cast<> here because we do not wish
3271 // to have a dependency of Type.h on Stmt.h/Expr.h.
3272 return (Expr*) SizeExpr;
3273 }
3274
3275 SourceRange getBracketsRange() const { return Brackets; }
3276 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3277 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3278
3279 bool isSugared() const { return false; }
3280 QualType desugar() const { return QualType(this, 0); }
3281
3282 static bool classof(const Type *T) {
3283 return T->getTypeClass() == DependentSizedArray;
3284 }
3285
3286 void Profile(llvm::FoldingSetNodeID &ID) {
3287 Profile(ID, Context, getElementType(),
3289 }
3290
3291 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3292 QualType ET, ArraySizeModifier SizeMod,
3293 unsigned TypeQuals, Expr *E);
3294};
3295
3296/// Represents an extended address space qualifier where the input address space
3297/// value is dependent. Non-dependent address spaces are not represented with a
3298/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3299///
3300/// For example:
3301/// \code
3302/// template<typename T, int AddrSpace>
3303/// class AddressSpace {
3304/// typedef T __attribute__((address_space(AddrSpace))) type;
3305/// }
3306/// \endcode
3307class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3308 friend class ASTContext;
3309
3310 const ASTContext &Context;
3311 Expr *AddrSpaceExpr;
3312 QualType PointeeType;
3313 SourceLocation loc;
3314
3315 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3316 QualType can, Expr *AddrSpaceExpr,
3317 SourceLocation loc);
3318
3319public:
3320 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3321 QualType getPointeeType() const { return PointeeType; }
3322 SourceLocation getAttributeLoc() const { return loc; }
3323
3324 bool isSugared() const { return false; }
3325 QualType desugar() const { return QualType(this, 0); }
3326
3327 static bool classof(const Type *T) {
3328 return T->getTypeClass() == DependentAddressSpace;
3329 }
3330
3331 void Profile(llvm::FoldingSetNodeID &ID) {
3332 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3333 }
3334
3335 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3336 QualType PointeeType, Expr *AddrSpaceExpr);
3337};
3338
3339/// Represents an extended vector type where either the type or size is
3340/// dependent.
3341///
3342/// For example:
3343/// \code
3344/// template<typename T, int Size>
3345/// class vector {
3346/// typedef T __attribute__((ext_vector_type(Size))) type;
3347/// }
3348/// \endcode
3349class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3350 friend class ASTContext;
3351
3352 const ASTContext &Context;
3353 Expr *SizeExpr;
3354
3355 /// The element type of the array.
3356 QualType ElementType;
3357
3358 SourceLocation loc;
3359
3360 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3361 QualType can, Expr *SizeExpr, SourceLocation loc);
3362
3363public:
3364 Expr *getSizeExpr() const { return SizeExpr; }
3365 QualType getElementType() const { return ElementType; }
3366 SourceLocation getAttributeLoc() const { return loc; }
3367
3368 bool isSugared() const { return false; }
3369 QualType desugar() const { return QualType(this, 0); }
3370
3371 static bool classof(const Type *T) {
3372 return T->getTypeClass() == DependentSizedExtVector;
3373 }
3374
3375 void Profile(llvm::FoldingSetNodeID &ID) {
3376 Profile(ID, Context, getElementType(), getSizeExpr());
3377 }
3378
3379 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3380 QualType ElementType, Expr *SizeExpr);
3381};
3382
3383
3384/// Represents a GCC generic vector type. This type is created using
3385/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3386/// bytes; or from an Altivec __vector or vector declaration.
3387/// Since the constructor takes the number of vector elements, the
3388/// client is responsible for converting the size into the number of elements.
3389class VectorType : public Type, public llvm::FoldingSetNode {
3390public:
3392 /// not a target-specific vector type
3394
3395 /// is AltiVec vector
3397
3398 /// is AltiVec 'vector Pixel'
3400
3401 /// is AltiVec 'vector bool ...'
3403
3404 /// is ARM Neon vector
3406
3407 /// is ARM Neon polynomial vector
3409
3410 /// is AArch64 SVE fixed-length data vector
3412
3413 /// is AArch64 SVE fixed-length predicate vector
3415
3416 /// is RISC-V RVV fixed-length data vector
3418 };
3419
3420protected:
3421 friend class ASTContext; // ASTContext creates these.
3422
3423 /// The element type of the vector.
3425
3426 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3427 VectorKind vecKind);
3428
3429 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3430 QualType canonType, VectorKind vecKind);
3431
3432public:
3434 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3435
3436 bool isSugared() const { return false; }
3437 QualType desugar() const { return QualType(this, 0); }
3438
3440 return VectorKind(VectorTypeBits.VecKind);
3441 }
3442
3443 void Profile(llvm::FoldingSetNodeID &ID) {
3446 }
3447
3448 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3449 unsigned NumElements, TypeClass TypeClass,
3450 VectorKind VecKind) {
3451 ID.AddPointer(ElementType.getAsOpaquePtr());
3452 ID.AddInteger(NumElements);
3453 ID.AddInteger(TypeClass);
3454 ID.AddInteger(VecKind);
3455 }
3456
3457 static bool classof(const Type *T) {
3458 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3459 }
3460};
3461
3462/// Represents a vector type where either the type or size is dependent.
3463////
3464/// For example:
3465/// \code
3466/// template<typename T, int Size>
3467/// class vector {
3468/// typedef T __attribute__((vector_size(Size))) type;
3469/// }
3470/// \endcode
3471class DependentVectorType : public Type, public llvm::FoldingSetNode {
3472 friend class ASTContext;
3473
3474 const ASTContext &Context;
3475 QualType ElementType;
3476 Expr *SizeExpr;
3477 SourceLocation Loc;
3478
3479 DependentVectorType(const ASTContext &Context, QualType ElementType,
3480 QualType CanonType, Expr *SizeExpr,
3482
3483public:
3484 Expr *getSizeExpr() const { return SizeExpr; }
3485 QualType getElementType() const { return ElementType; }
3486 SourceLocation getAttributeLoc() const { return Loc; }
3488 return VectorType::VectorKind(VectorTypeBits.VecKind);
3489 }
3490
3491 bool isSugared() const { return false; }
3492 QualType desugar() const { return QualType(this, 0); }
3493
3494 static bool classof(const Type *T) {
3495 return T->getTypeClass() == DependentVector;
3496 }
3497
3498 void Profile(llvm::FoldingSetNodeID &ID) {
3499 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3500 }
3501
3502 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3503 QualType ElementType, const Expr *SizeExpr,
3504 VectorType::VectorKind VecKind);
3505};
3506
3507/// ExtVectorType - Extended vector type. This type is created using
3508/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3509/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3510/// class enables syntactic extensions, like Vector Components for accessing
3511/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3512/// Shading Language).
3514 friend class ASTContext; // ASTContext creates these.
3515
3516 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3517 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3518
3519public:
3520 static int getPointAccessorIdx(char c) {
3521 switch (c) {
3522 default: return -1;
3523 case 'x': case 'r': return 0;
3524 case 'y': case 'g': return 1;
3525 case 'z': case 'b': return 2;
3526 case 'w': case 'a': return 3;
3527 }
3528 }
3529
3530 static int getNumericAccessorIdx(char c) {
3531 switch (c) {
3532 default: return -1;
3533 case '0': return 0;
3534 case '1': return 1;
3535 case '2': return 2;
3536 case '3': return 3;
3537 case '4': return 4;
3538 case '5': return 5;
3539 case '6': return 6;
3540 case '7': return 7;
3541 case '8': return 8;
3542 case '9': return 9;
3543 case 'A':
3544 case 'a': return 10;
3545 case 'B':
3546 case 'b': return 11;
3547 case 'C':
3548 case 'c': return 12;
3549 case 'D':
3550 case 'd': return 13;
3551 case 'E':
3552 case 'e': return 14;
3553 case 'F':
3554 case 'f': return 15;
3555 }
3556 }
3557
3558 static int getAccessorIdx(char c, bool isNumericAccessor) {
3559 if (isNumericAccessor)
3560 return getNumericAccessorIdx(c);
3561 else
3562 return getPointAccessorIdx(c);
3563 }
3564
3565 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3566 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3567 return unsigned(idx-1) < getNumElements();
3568 return false;
3569 }
3570
3571 bool isSugared() const { return false; }
3572 QualType desugar() const { return QualType(this, 0); }
3573
3574 static bool classof(const Type *T) {
3575 return T->getTypeClass() == ExtVector;
3576 }
3577};
3578
3579/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3580/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3581/// number of rows and "columns" specifies the number of columns.
3582class MatrixType : public Type, public llvm::FoldingSetNode {
3583protected:
3584 friend class ASTContext;
3585
3586 /// The element type of the matrix.
3588
3589 MatrixType(QualType ElementTy, QualType CanonElementTy);
3590
3591 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3592 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3593
3594public:
3595 /// Returns type of the elements being stored in the matrix
3597
3598 /// Valid elements types are the following:
3599 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3600 /// and _Bool
3601 /// * the standard floating types float or double
3602 /// * a half-precision floating point type, if one is supported on the target
3604 return T->isDependentType() ||
3605 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3606 }
3607
3608 bool isSugared() const { return false; }
3609 QualType desugar() const { return QualType(this, 0); }
3610
3611 static bool classof(const Type *T) {
3612 return T->getTypeClass() == ConstantMatrix ||
3613 T->getTypeClass() == DependentSizedMatrix;
3614 }
3615};
3616
3617/// Represents a concrete matrix type with constant number of rows and columns
3618class ConstantMatrixType final : public MatrixType {
3619protected:
3620 friend class ASTContext;
3621
3622 /// Number of rows and columns.
3623 unsigned NumRows;
3624 unsigned NumColumns;
3625
3626 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3627
3628 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3629 unsigned NColumns, QualType CanonElementType);
3630
3631 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3632 unsigned NColumns, QualType CanonElementType);
3633
3634public:
3635 /// Returns the number of rows in the matrix.
3636 unsigned getNumRows() const { return NumRows; }
3637
3638 /// Returns the number of columns in the matrix.
3639 unsigned getNumColumns() const { return NumColumns; }
3640
3641 /// Returns the number of elements required to embed the matrix into a vector.
3642 unsigned getNumElementsFlattened() const {
3643 return getNumRows() * getNumColumns();
3644 }
3645
3646 /// Returns true if \p NumElements is a valid matrix dimension.
3647 static constexpr bool isDimensionValid(size_t NumElements) {
3648 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3649 }
3650
3651 /// Returns the maximum number of elements per dimension.
3652 static constexpr unsigned getMaxElementsPerDimension() {
3654 }
3655
3656 void Profile(llvm::FoldingSetNodeID &ID) {
3658 getTypeClass());
3659 }
3660
3661 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3662 unsigned NumRows, unsigned NumColumns,
3664 ID.AddPointer(ElementType.getAsOpaquePtr());
3665 ID.AddInteger(NumRows);
3666 ID.AddInteger(NumColumns);
3667 ID.AddInteger(TypeClass);
3668 }
3669
3670 static bool classof(const Type *T) {
3671 return T->getTypeClass() == ConstantMatrix;
3672 }
3673};
3674
3675/// Represents a matrix type where the type and the number of rows and columns
3676/// is dependent on a template.
3678 friend class ASTContext;
3679
3680 const ASTContext &Context;
3681 Expr *RowExpr;
3682 Expr *ColumnExpr;
3683
3684 SourceLocation loc;
3685
3687 QualType CanonicalType, Expr *RowExpr,
3688 Expr *ColumnExpr, SourceLocation loc);
3689
3690public:
3691 Expr *getRowExpr() const { return RowExpr; }
3692 Expr *getColumnExpr() const { return ColumnExpr; }
3693 SourceLocation getAttributeLoc() const { return loc; }
3694
3695 static bool classof(const Type *T) {
3696 return T->getTypeClass() == DependentSizedMatrix;
3697 }
3698
3699 void Profile(llvm::FoldingSetNodeID &ID) {
3700 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3701 }
3702
3703 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3704 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3705};
3706
3707/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3708/// class of FunctionNoProtoType and FunctionProtoType.
3709class FunctionType : public Type {
3710 // The type returned by the function.
3711 QualType ResultType;
3712
3713public:
3714 /// Interesting information about a specific parameter that can't simply
3715 /// be reflected in parameter's type. This is only used by FunctionProtoType
3716 /// but is in FunctionType to make this class available during the
3717 /// specification of the bases of FunctionProtoType.
3718 ///
3719 /// It makes sense to model language features this way when there's some
3720 /// sort of parameter-specific override (such as an attribute) that
3721 /// affects how the function is called. For example, the ARC ns_consumed
3722 /// attribute changes whether a parameter is passed at +0 (the default)
3723 /// or +1 (ns_consumed). This must be reflected in the function type,
3724 /// but isn't really a change to the parameter type.
3725 ///
3726 /// One serious disadvantage of modelling language features this way is
3727 /// that they generally do not work with language features that attempt
3728 /// to destructure types. For example, template argument deduction will
3729 /// not be able to match a parameter declared as
3730 /// T (*)(U)
3731 /// against an argument of type
3732 /// void (*)(__attribute__((ns_consumed)) id)
3733 /// because the substitution of T=void, U=id into the former will
3734 /// not produce the latter.
3736 enum {
3737 ABIMask = 0x0F,
3738 IsConsumed = 0x10,
3739 HasPassObjSize = 0x20,
3740 IsNoEscape = 0x40,
3741 };
3742 unsigned char Data = 0;
3743
3744 public:
3745 ExtParameterInfo() = default;
3746
3747 /// Return the ABI treatment of this parameter.
3748 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3750 ExtParameterInfo copy = *this;
3751 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3752 return copy;
3753 }
3754
3755 /// Is this parameter considered "consumed" by Objective-C ARC?
3756 /// Consumed parameters must have retainable object type.
3757 bool isConsumed() const { return (Data & IsConsumed); }
3758 ExtParameterInfo withIsConsumed(bool consumed) const {
3759 ExtParameterInfo copy = *this;
3760 if (consumed)
3761 copy.Data |= IsConsumed;
3762 else
3763 copy.Data &= ~IsConsumed;
3764 return copy;
3765 }
3766
3767 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3769 ExtParameterInfo Copy = *this;
3770 Copy.Data |= HasPassObjSize;
3771 return Copy;
3772 }
3773
3774 bool isNoEscape() const { return Data & IsNoEscape; }
3775 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3776 ExtParameterInfo Copy = *this;
3777 if (NoEscape)
3778 Copy.Data |= IsNoEscape;
3779 else
3780 Copy.Data &= ~IsNoEscape;
3781 return Copy;
3782 }
3783
3784 unsigned char getOpaqueValue() const { return Data; }
3785 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3786 ExtParameterInfo result;
3787 result.Data = data;
3788 return result;
3789 }
3790
3792 return lhs.Data == rhs.Data;
3793 }
3794
3796 return lhs.Data != rhs.Data;
3797 }
3798 };
3799
3800 /// A class which abstracts out some details necessary for
3801 /// making a call.
3802 ///
3803 /// It is not actually used directly for storing this information in
3804 /// a FunctionType, although FunctionType does currently use the
3805 /// same bit-pattern.
3806 ///
3807 // If you add a field (say Foo), other than the obvious places (both,
3808 // constructors, compile failures), what you need to update is
3809 // * Operator==
3810 // * getFoo
3811 // * withFoo
3812 // * functionType. Add Foo, getFoo.
3813 // * ASTContext::getFooType
3814 // * ASTContext::mergeFunctionTypes
3815 // * FunctionNoProtoType::Profile
3816 // * FunctionProtoType::Profile
3817 // * TypePrinter::PrintFunctionProto
3818 // * AST read and write
3819 // * Codegen
3820 class ExtInfo {
3821 friend class FunctionType;
3822
3823 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3824 // adjust the Bits field below, and if you add bits, you'll need to adjust
3825 // Type::FunctionTypeBitfields::ExtInfo as well.
3826
3827 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3828 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3829 //
3830 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3831 enum { CallConvMask = 0x1F };
3832 enum { NoReturnMask = 0x20 };
3833 enum { ProducesResultMask = 0x40 };
3834 enum { NoCallerSavedRegsMask = 0x80 };
3835 enum {
3836 RegParmMask = 0x700,
3837 RegParmOffset = 8
3838 };
3839 enum { NoCfCheckMask = 0x800 };
3840 enum { CmseNSCallMask = 0x1000 };
3841 uint16_t Bits = CC_C;
3842
3843 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3844
3845 public:
3846 // Constructor with no defaults. Use this when you know that you
3847 // have all the elements (when reading an AST file for example).
3848 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3849 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3850 bool cmseNSCall) {
3851 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3852 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3853 (producesResult ? ProducesResultMask : 0) |
3854 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3855 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3856 (NoCfCheck ? NoCfCheckMask : 0) |
3857 (cmseNSCall ? CmseNSCallMask : 0);
3858 }
3859
3860 // Constructor with all defaults. Use when for example creating a
3861 // function known to use defaults.
3862 ExtInfo() = default;
3863
3864 // Constructor with just the calling convention, which is an important part
3865 // of the canonical type.
3866 ExtInfo(CallingConv CC) : Bits(CC) {}
3867
3868 bool getNoReturn() const { return Bits & NoReturnMask; }
3869 bool getProducesResult() const { return Bits & ProducesResultMask; }
3870 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3871 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3872 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3873 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3874
3875 unsigned getRegParm() const {
3876 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3877 if (RegParm > 0)
3878 --RegParm;
3879 return RegParm;
3880 }
3881
3882 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3883
3884 bool operator==(ExtInfo Other) const {
3885 return Bits == Other.Bits;
3886 }
3887 bool operator!=(ExtInfo Other) const {
3888 return Bits != Other.Bits;
3889 }
3890
3891 // Note that we don't have setters. That is by design, use
3892 // the following with methods instead of mutating these objects.
3893
3894 ExtInfo withNoReturn(bool noReturn) const {
3895 if (noReturn)
3896 return ExtInfo(Bits | NoReturnMask);
3897 else
3898 return ExtInfo(Bits & ~NoReturnMask);
3899 }
3900
3901 ExtInfo withProducesResult(bool producesResult) const {
3902 if (producesResult)
3903 return ExtInfo(Bits | ProducesResultMask);
3904 else
3905 return ExtInfo(Bits & ~ProducesResultMask);
3906 }
3907
3908 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3909 if (cmseNSCall)
3910 return ExtInfo(Bits | CmseNSCallMask);
3911 else
3912 return ExtInfo(Bits & ~CmseNSCallMask);
3913 }
3914
3915 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3916 if (noCallerSavedRegs)
3917 return ExtInfo(Bits | NoCallerSavedRegsMask);
3918 else
3919 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3920 }
3921
3922 ExtInfo withNoCfCheck(bool noCfCheck) const {
3923 if (noCfCheck)
3924 return ExtInfo(Bits | NoCfCheckMask);
3925 else
3926 return ExtInfo(Bits & ~NoCfCheckMask);
3927 }
3928
3929 ExtInfo withRegParm(unsigned RegParm) const {
3930 assert(RegParm < 7 && "Invalid regparm value");
3931 return ExtInfo((Bits & ~RegParmMask) |
3932 ((RegParm + 1) << RegParmOffset));
3933 }
3934
3936 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3937 }
3938
3939 void Profile(llvm::FoldingSetNodeID &ID) const {
3940 ID.AddInteger(Bits);
3941 }
3942 };
3943
3944 /// A simple holder for a QualType representing a type in an
3945 /// exception specification. Unfortunately needed by FunctionProtoType
3946 /// because TrailingObjects cannot handle repeated types.
3948
3949 /// A simple holder for various uncommon bits which do not fit in
3950 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3951 /// alignment of subsequent objects in TrailingObjects.
3952 struct alignas(void *) FunctionTypeExtraBitfields {
3953 /// The number of types in the exception specification.
3954 /// A whole unsigned is not needed here and according to
3955 /// [implimits] 8 bits would be enough here.
3956 unsigned NumExceptionType = 0;
3957 };
3958
3959protected:
3962 : Type(tc, Canonical, Dependence), ResultType(res) {
3963 FunctionTypeBits.ExtInfo = Info.Bits;
3964 }
3965
3967 if (isFunctionProtoType())
3968 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3969
3970 return Qualifiers();
3971 }
3972
3973public:
3974 QualType getReturnType() const { return ResultType; }
3975
3976 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3977 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3978
3979 /// Determine whether this function type includes the GNU noreturn
3980 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3981 /// type.
3982 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3983
3984 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3985 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3986 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3987
3988 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3989 "Const, volatile and restrict are assumed to be a subset of "
3990 "the fast qualifiers.");
3991
3992 bool isConst() const { return getFastTypeQuals().hasConst(); }
3993 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3994 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3995
3996 /// Determine the type of an expression that calls a function of
3997 /// this type.
3998 QualType getCallResultType(const ASTContext &Context) const {
3999 return getReturnType().getNonLValueExprType(Context);
4000 }
4001
4002 static StringRef getNameForCallConv(CallingConv CC);
4003
4004 static bool classof(const Type *T) {
4005 return T->getTypeClass() == FunctionNoProto ||
4006 T->getTypeClass() == FunctionProto;
4007 }
4008};
4009
4010/// Represents a K&R-style 'int foo()' function, which has
4011/// no information available about its arguments.
4012class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
4013 friend class ASTContext; // ASTContext creates these.
4014
4016 : FunctionType(FunctionNoProto, Result, Canonical,
4018 ~(TypeDependence::DependentInstantiation |
4019 TypeDependence::UnexpandedPack),
4020 Info) {}
4021
4022public:
4023 // No additional state past what FunctionType provides.
4024
4025 bool isSugared() const { return false; }
4026 QualType desugar() const { return QualType(this, 0); }
4027
4028 void Profile(llvm::FoldingSetNodeID &ID) {
4030 }
4031
4032 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
4033 ExtInfo Info) {
4034 Info.Profile(ID);
4035 ID.AddPointer(ResultType.getAsOpaquePtr());
4036 }
4037
4038 static bool classof(const Type *T) {
4039 return T->getTypeClass() == FunctionNoProto;
4040 }
4041};
4042
4043/// Represents a prototype with parameter type info, e.g.
4044/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
4045/// parameters, not as having a single void parameter. Such a type can have
4046/// an exception specification, but this specification is not part of the
4047/// canonical type. FunctionProtoType has several trailing objects, some of
4048/// which optional. For more information about the trailing objects see
4049/// the first comment inside FunctionProtoType.
4051 : public FunctionType,
4052 public llvm::FoldingSetNode,
4053 private llvm::TrailingObjects<
4054 FunctionProtoType, QualType, SourceLocation,
4055 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
4056 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
4057 friend class ASTContext; // ASTContext creates these.
4058 friend TrailingObjects;
4059
4060 // FunctionProtoType is followed by several trailing objects, some of
4061 // which optional. They are in order:
4062 //
4063 // * An array of getNumParams() QualType holding the parameter types.
4064 // Always present. Note that for the vast majority of FunctionProtoType,
4065 // these will be the only trailing objects.
4066 //
4067 // * Optionally if the function is variadic, the SourceLocation of the
4068 // ellipsis.
4069 //
4070 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
4071 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
4072 // a single FunctionTypeExtraBitfields. Present if and only if
4073 // hasExtraBitfields() is true.
4074 //
4075 // * Optionally exactly one of:
4076 // * an array of getNumExceptions() ExceptionType,
4077 // * a single Expr *,
4078 // * a pair of FunctionDecl *,
4079 // * a single FunctionDecl *
4080 // used to store information about the various types of exception
4081 // specification. See getExceptionSpecSize for the details.
4082 //
4083 // * Optionally an array of getNumParams() ExtParameterInfo holding
4084 // an ExtParameterInfo for each of the parameters. Present if and
4085 // only if hasExtParameterInfos() is true.
4086 //
4087 // * Optionally a Qualifiers object to represent extra qualifiers that can't
4088 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
4089 // if hasExtQualifiers() is true.
4090 //
4091 // The optional FunctionTypeExtraBitfields has to be before the data
4092 // related to the exception specification since it contains the number
4093 // of exception types.
4094 //
4095 // We put the ExtParameterInfos last. If all were equal, it would make
4096 // more sense to put these before the exception specification, because
4097 // it's much easier to skip past them compared to the elaborate switch
4098 // required to skip the exception specification. However, all is not
4099 // equal; ExtParameterInfos are used to model very uncommon features,
4100 // and it's better not to burden the more common paths.
4101
4102public:
4103 /// Holds information about the various types of exception specification.
4104 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
4105 /// used to group together the various bits of information about the
4106 /// exception specification.
4108 /// The kind of exception specification this is.
4110
4111 /// Explicitly-specified list of exception types.
4113
4114 /// Noexcept expression, if this is a computed noexcept specification.
4115 Expr *NoexceptExpr = nullptr;
4116
4117 /// The function whose exception specification this is, for
4118 /// EST_Unevaluated and EST_Uninstantiated.
4120
4121 /// The function template whose exception specification this is instantiated
4122 /// from, for EST_Uninstantiated.
4124
4126
4128 };
4129
4130 /// Extra information about a function prototype. ExtProtoInfo is not
4131 /// stored as such in FunctionProtoType but is used to group together
4132 /// the various bits of extra information about a function prototype.
4135 bool Variadic : 1;
4142
4144
4147
4149 ExtProtoInfo Result(*this);
4150 Result.ExceptionSpec = ESI;
4151 return Result;
4152 }
4153
4155 return ExceptionSpec.Type == EST_Dynamic;
4156 }
4157 };
4158
4159private:
4160 unsigned numTrailingObjects(OverloadToken<QualType>) const {
4161 return getNumParams();
4162 }
4163
4164 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
4165 return isVariadic();
4166 }
4167
4168 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
4169 return hasExtraBitfields();
4170 }
4171
4172 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4173 return getExceptionSpecSize().NumExceptionType;
4174 }
4175
4176 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4177 return getExceptionSpecSize().NumExprPtr;
4178 }
4179
4180 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4181 return getExceptionSpecSize().NumFunctionDeclPtr;
4182 }
4183
4184 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4185 return hasExtParameterInfos() ? getNumParams() : 0;
4186 }
4187
4188 /// Determine whether there are any argument types that
4189 /// contain an unexpanded parameter pack.
4190 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4191 unsigned numArgs) {
4192 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4193 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4194 return true;
4195
4196 return false;
4197 }
4198
4199 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4200 QualType canonical, const ExtProtoInfo &epi);
4201
4202 /// This struct is returned by getExceptionSpecSize and is used to
4203 /// translate an ExceptionSpecificationType to the number and kind
4204 /// of trailing objects related to the exception specification.
4205 struct ExceptionSpecSizeHolder {
4206 unsigned NumExceptionType;
4207 unsigned NumExprPtr;
4208 unsigned NumFunctionDeclPtr;
4209 };
4210
4211 /// Return the number and kind of trailing objects
4212 /// related to the exception specification.
4213 static ExceptionSpecSizeHolder
4214 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4215 switch (EST) {
4216 case EST_None:
4217 case EST_DynamicNone:
4218 case EST_MSAny:
4219 case EST_BasicNoexcept:
4220 case EST_Unparsed:
4221 case EST_NoThrow:
4222 return {0, 0, 0};
4223
4224 case EST_Dynamic:
4225 return {NumExceptions, 0, 0};
4226
4228 case EST_NoexceptFalse:
4229 case EST_NoexceptTrue:
4230 return {0, 1, 0};
4231
4232 case EST_Uninstantiated:
4233 return {0, 0, 2};
4234
4235 case EST_Unevaluated:
4236 return {0, 0, 1};
4237 }
4238 llvm_unreachable("bad exception specification kind");
4239 }
4240
4241 /// Return the number and kind of trailing objects
4242 /// related to the exception specification.
4243 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4244 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4245 }
4246
4247 /// Whether the trailing FunctionTypeExtraBitfields is present.
4248 bool hasExtraBitfields() const {
4249 assert((getExceptionSpecType() != EST_Dynamic ||
4250 FunctionTypeBits.HasExtraBitfields) &&
4251 "ExtraBitfields are required for given ExceptionSpecType");
4252 return FunctionTypeBits.HasExtraBitfields;
4253
4254 }
4255
4256 bool hasExtQualifiers() const {
4257 return FunctionTypeBits.HasExtQuals;
4258 }
4259
4260public:
4261 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4262
4263 QualType getParamType(unsigned i) const {
4264 assert(i < getNumParams() && "invalid parameter index");
4265 return param_type_begin()[i];
4266 }
4267
4270 }
4271
4273 ExtProtoInfo EPI;
4274 EPI.ExtInfo = getExtInfo();
4275 EPI.Variadic = isVariadic();
4279 EPI.TypeQuals = getMethodQuals();
4282 return EPI;
4283 }
4284
4285 /// Get the kind of exception specification on this function.
4287 return static_cast<ExceptionSpecificationType>(
4288 FunctionTypeBits.ExceptionSpecType);
4289 }
4290
4291 /// Return whether this function has any kind of exception spec.
4292 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4293
4294 /// Return whether this function has a dynamic (throw) exception spec.
4297 }
4298
4299 /// Return whether this function has a noexcept exception spec.
4302 }
4303
4304 /// Return whether this function has a dependent exception spec.
4305 bool hasDependentExceptionSpec() const;
4306
4307 /// Return whether this function has an instantiation-dependent exception
4308 /// spec.
4310
4311 /// Return all the available information about this type's exception spec.
4315 if (Result.Type == EST_Dynamic) {
4316 Result.Exceptions = exceptions();
4317 } else if (isComputedNoexcept(Result.Type)) {
4318 Result.NoexceptExpr = getNoexceptExpr();
4319 } else if (Result.Type == EST_Uninstantiated) {
4320 Result.SourceDecl = getExceptionSpecDecl();
4321 Result.SourceTemplate = getExceptionSpecTemplate();
4322 } else if (Result.Type == EST_Unevaluated) {
4323 Result.SourceDecl = getExceptionSpecDecl();
4324 }
4325 return Result;
4326 }
4327
4328 /// Return the number of types in the exception specification.
4329 unsigned getNumExceptions() const {
4331 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4332 ->NumExceptionType
4333 : 0;
4334 }
4335
4336 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4337 QualType getExceptionType(unsigned i) const {
4338 assert(i < getNumExceptions() && "Invalid exception number!");
4339 return exception_begin()[i];
4340 }
4341
4342 /// Return the expression inside noexcept(expression), or a null pointer
4343 /// if there is none (because the exception spec is not of this form).
4346 return nullptr;
4347 return *getTrailingObjects<Expr *>();
4348 }
4349
4350 /// If this function type has an exception specification which hasn't
4351 /// been determined yet (either because it has not been evaluated or because
4352 /// it has not been instantiated), this is the function whose exception
4353 /// specification is represented by this type.
4357 return nullptr;
4358 return getTrailingObjects<FunctionDecl *>()[0];
4359 }
4360
4361 /// If this function type has an uninstantiated exception
4362 /// specification, this is the function whose exception specification
4363 /// should be instantiated to find the exception specification for
4364 /// this type.
4367 return nullptr;
4368 return getTrailingObjects<FunctionDecl *>()[1];
4369 }
4370
4371 /// Determine whether this function type has a non-throwing exception
4372 /// specification.
4373 CanThrowResult canThrow() const;
4374
4375 /// Determine whether this function type has a non-throwing exception
4376 /// specification. If this depends on template arguments, returns
4377 /// \c ResultIfDependent.
4378 bool isNothrow(bool ResultIfDependent = false) const {
4379 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4380 }
4381
4382 /// Whether this function prototype is variadic.
4383 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4384
4386 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4387 : SourceLocation();
4388 }
4389
4390 /// Determines whether this function prototype contains a
4391 /// parameter pack at the end.
4392 ///
4393 /// A function template whose last parameter is a parameter pack can be
4394 /// called with an arbitrary number of arguments, much like a variadic
4395 /// function.
4396 bool isTemplateVariadic() const;
4397
4398 /// Whether this function prototype has a trailing return type.
4399 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4400
4402 if (hasExtQualifiers())
4403 return *getTrailingObjects<Qualifiers>();
4404 else
4405 return getFastTypeQuals();
4406 }
4407
4408 /// Retrieve the ref-qualifier associated with this function type.
4410 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4411 }
4412
4414
4417 }
4418
4420 return getTrailingObjects<QualType>();
4421 }
4422
4424 return param_type_begin() + getNumParams();
4425 }
4426
4428
4431 }
4432
4434 return reinterpret_cast<exception_iterator>(
4435 getTrailingObjects<ExceptionType>());
4436 }
4437
4439 return exception_begin() + getNumExceptions();
4440 }
4441
4442 /// Is there any interesting extra information for any of the parameters
4443 /// of this function type?
4445 return FunctionTypeBits.HasExtParameterInfos;
4446 }
4447
4449 assert(hasExtParameterInfos());
4450 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4451 getNumParams());
4452 }
4453
4454 /// Return a pointer to the beginning of the array of extra parameter
4455 /// information, if present, or else null if none of the parameters
4456 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4458 if (!hasExtParameterInfos())
4459 return nullptr;
4460 return getTrailingObjects<ExtParameterInfo>();
4461 }
4462
4464 assert(I < getNumParams() && "parameter index out of range");
4466 return getTrailingObjects<ExtParameterInfo>()[I];
4467 return ExtParameterInfo();
4468 }
4469
4470 ParameterABI getParameterABI(unsigned I) const {
4471 assert(I < getNumParams() && "parameter index out of range");
4473 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4475 }
4476
4477 bool isParamConsumed(unsigned I) const {
4478 assert(I < getNumParams() && "parameter index out of range");
4480 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4481 return false;
4482 }
4483
4484 bool isSugared() const { return false; }
4485 QualType desugar() const { return QualType(this, 0); }
4486
4487 void printExceptionSpecification(raw_ostream &OS,
4488 const PrintingPolicy &Policy) const;
4489
4490 static bool classof(const Type *T) {
4491 return T->getTypeClass() == FunctionProto;
4492 }
4493
4494 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4495 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4496 param_type_iterator ArgTys, unsigned NumArgs,
4497 const ExtProtoInfo &EPI, const ASTContext &Context,
4498 bool Canonical);
4499};
4500
4501/// Represents the dependent type named by a dependently-scoped
4502/// typename using declaration, e.g.
4503/// using typename Base<T>::foo;
4504///
4505/// Template instantiation turns these into the underlying type.
4507 friend class ASTContext; // ASTContext creates these.
4508
4510
4512 : Type(UnresolvedUsing, QualType(),
4513 TypeDependence::DependentInstantiation),
4514 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4515
4516public:
4518
4519 bool isSugared() const { return false; }
4520 QualType desugar() const { return QualType(this, 0); }
4521
4522 static bool classof(const Type *T) {
4523 return T->getTypeClass() == UnresolvedUsing;
4524 }
4525
4526 void Profile(llvm::FoldingSetNodeID &ID) {
4527 return Profile(ID, Decl);
4528 }
4529
4530 static void Profile(llvm::FoldingSetNodeID &ID,
4532 ID.AddPointer(D);
4533 }
4534};
4535
4536class UsingType final : public Type,
4537 public llvm::FoldingSetNode,
4538 private llvm::TrailingObjects<UsingType, QualType> {
4539 UsingShadowDecl *Found;
4540 friend class ASTContext; // ASTContext creates these.
4541 friend TrailingObjects;
4542
4543 UsingType(const UsingShadowDecl *Found, QualType Underlying, QualType Canon);
4544
4545public:
4546 UsingShadowDecl *getFoundDecl() const { return Found; }
4548
4549 bool isSugared() const { return true; }
4550
4551 // This always has the 'same' type as declared, but not necessarily identical.
4552 QualType desugar() const { return getUnderlyingType(); }
4553
4554 // Internal helper, for debugging purposes.
4555 bool typeMatchesDecl() const { return !UsingBits.hasTypeDifferentFromDecl; }
4556
4557 void Profile(llvm::FoldingSetNodeID &ID) {
4558 Profile(ID, Found, typeMatchesDecl() ? QualType() : getUnderlyingType());
4559 }
4560 static void Profile(llvm::FoldingSetNodeID &ID, const UsingShadowDecl *Found,
4561 QualType Underlying) {
4562 ID.AddPointer(Found);
4563 if (!Underlying.isNull())
4564 Underlying.Profile(ID);
4565 }
4566 static bool classof(const Type *T) { return T->getTypeClass() == Using; }
4567};
4568
4569class TypedefType final : public Type,
4570 public llvm::FoldingSetNode,
4571 private llvm::TrailingObjects<TypedefType, QualType> {
4573 friend class ASTContext; // ASTContext creates these.
4574 friend TrailingObjects;
4575
4576 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4577 QualType can);
4578
4579public: