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