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
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/PointerIntPair.h"
38#include "llvm/ADT/PointerUnion.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include "llvm/Support/type_traits.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <optional>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class BTFTypeTagAttr;
61class ExtQuals;
62class QualType;
63class ConceptDecl;
64class ValueDecl;
65class TagDecl;
66class TemplateParameterList;
67class Type;
68
69enum {
70 TypeAlignmentInBits = 4,
71 TypeAlignment = 1 << TypeAlignmentInBits
72};
73
74namespace serialization {
75 template <class T> class AbstractTypeReader;
76 template <class T> class AbstractTypeWriter;
77}
78
79} // namespace clang
80
81namespace llvm {
82
83 template <typename T>
84 struct PointerLikeTypeTraits;
85 template<>
86 struct PointerLikeTypeTraits< ::clang::Type*> {
87 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
88
89 static inline ::clang::Type *getFromVoidPointer(void *P) {
90 return static_cast< ::clang::Type*>(P);
91 }
92
93 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
94 };
95
96 template<>
97 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
98 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
99
100 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
101 return static_cast< ::clang::ExtQuals*>(P);
102 }
103
104 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
105 };
106
107} // namespace llvm
108
109namespace clang {
110
111class ASTContext;
112template <typename> class CanQual;
113class CXXRecordDecl;
114class DeclContext;
115class EnumDecl;
116class Expr;
117class ExtQualsTypeCommonBase;
118class FunctionDecl;
119class IdentifierInfo;
120class NamedDecl;
121class ObjCInterfaceDecl;
122class ObjCProtocolDecl;
123class ObjCTypeParamDecl;
124struct PrintingPolicy;
125class RecordDecl;
126class Stmt;
127class TagDecl;
128class TemplateArgument;
129class TemplateArgumentListInfo;
130class TemplateArgumentLoc;
131class TemplateTypeParmDecl;
132class TypedefNameDecl;
133class UnresolvedUsingTypenameDecl;
134class UsingShadowDecl;
135
136using CanQualType = CanQual<Type>;
137
138// Provide forward declarations for all of the *Type classes.
139#define TYPE(Class, Base) class Class##Type;
140#include "clang/AST/TypeNodes.inc"
141
142/// The collection of all-type qualifiers we support.
143/// Clang supports five independent qualifiers:
144/// * C99: const, volatile, and restrict
145/// * MS: __unaligned
146/// * Embedded C (TR18037): address spaces
147/// * Objective C: the GC attributes (none, weak, or strong)
148class Qualifiers {
149public:
150 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
151 Const = 0x1,
152 Restrict = 0x2,
153 Volatile = 0x4,
154 CVRMask = Const | Volatile | Restrict
155 };
156
157 enum GC {
158 GCNone = 0,
159 Weak,
160 Strong
161 };
162
163 enum ObjCLifetime {
164 /// There is no lifetime qualification on this type.
165 OCL_None,
166
167 /// This object can be modified without requiring retains or
168 /// releases.
169 OCL_ExplicitNone,
170
171 /// Assigning into this object requires the old value to be
172 /// released and the new value to be retained. The timing of the
173 /// release of the old value is inexact: it may be moved to
174 /// immediately after the last known point where the value is
175 /// live.
176 OCL_Strong,
177
178 /// Reading or writing from this object requires a barrier call.
179 OCL_Weak,
180
181 /// Assigning into this object requires a lifetime extension.
182 OCL_Autoreleasing
183 };
184
185 enum {
186 /// The maximum supported address space number.
187 /// 23 bits should be enough for anyone.
188 MaxAddressSpace = 0x7fffffu,
189
190 /// The width of the "fast" qualifier mask.
191 FastWidth = 3,
192
193 /// The fast qualifier mask.
194 FastMask = (1 << FastWidth) - 1
195 };
196
197 /// Returns the common set of qualifiers while removing them from
198 /// the given sets.
199 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
200 // If both are only CVR-qualified, bit operations are sufficient.
201 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
202 Qualifiers Q;
203 Q.Mask = L.Mask & R.Mask;
204 L.Mask &= ~Q.Mask;
205 R.Mask &= ~Q.Mask;
206 return Q;
207 }
208
209 Qualifiers Q;
210 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
211 Q.addCVRQualifiers(mask: CommonCRV);
212 L.removeCVRQualifiers(mask: CommonCRV);
213 R.removeCVRQualifiers(mask: CommonCRV);
214
215 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
216 Q.setObjCGCAttr(L.getObjCGCAttr());
217 L.removeObjCGCAttr();
218 R.removeObjCGCAttr();
219 }
220
221 if (L.getObjCLifetime() == R.getObjCLifetime()) {
222 Q.setObjCLifetime(L.getObjCLifetime());
223 L.removeObjCLifetime();
224 R.removeObjCLifetime();
225 }
226
227 if (L.getAddressSpace() == R.getAddressSpace()) {
228 Q.setAddressSpace(L.getAddressSpace());
229 L.removeAddressSpace();
230 R.removeAddressSpace();
231 }
232 return Q;
233 }
234
235 static Qualifiers fromFastMask(unsigned Mask) {
236 Qualifiers Qs;
237 Qs.addFastQualifiers(mask: Mask);
238 return Qs;
239 }
240
241 static Qualifiers fromCVRMask(unsigned CVR) {
242 Qualifiers Qs;
243 Qs.addCVRQualifiers(mask: CVR);
244 return Qs;
245 }
246
247 static Qualifiers fromCVRUMask(unsigned CVRU) {
248 Qualifiers Qs;
249 Qs.addCVRUQualifiers(mask: CVRU);
250 return Qs;
251 }
252
253 // Deserialize qualifiers from an opaque representation.
254 static Qualifiers fromOpaqueValue(unsigned opaque) {
255 Qualifiers Qs;
256 Qs.Mask = opaque;
257 return Qs;
258 }
259
260 // Serialize these qualifiers into an opaque representation.
261 unsigned getAsOpaqueValue() const {
262 return Mask;
263 }
264
265 bool hasConst() const { return Mask & Const; }
266 bool hasOnlyConst() const { return Mask == Const; }
267 void removeConst() { Mask &= ~Const; }
268 void addConst() { Mask |= Const; }
269 Qualifiers withConst() const {
270 Qualifiers Qs = *this;
271 Qs.addConst();
272 return Qs;
273 }
274
275 bool hasVolatile() const { return Mask & Volatile; }
276 bool hasOnlyVolatile() const { return Mask == Volatile; }
277 void removeVolatile() { Mask &= ~Volatile; }
278 void addVolatile() { Mask |= Volatile; }
279 Qualifiers withVolatile() const {
280 Qualifiers Qs = *this;
281 Qs.addVolatile();
282 return Qs;
283 }
284
285 bool hasRestrict() const { return Mask & Restrict; }
286 bool hasOnlyRestrict() const { return Mask == Restrict; }
287 void removeRestrict() { Mask &= ~Restrict; }
288 void addRestrict() { Mask |= Restrict; }
289 Qualifiers withRestrict() const {
290 Qualifiers Qs = *this;
291 Qs.addRestrict();
292 return Qs;
293 }
294
295 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
296 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
297 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
298
299 void setCVRQualifiers(unsigned mask) {
300 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
301 Mask = (Mask & ~CVRMask) | mask;
302 }
303 void removeCVRQualifiers(unsigned mask) {
304 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
305 Mask &= ~mask;
306 }
307 void removeCVRQualifiers() {
308 removeCVRQualifiers(mask: CVRMask);
309 }
310 void addCVRQualifiers(unsigned mask) {
311 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
312 Mask |= mask;
313 }
314 void addCVRUQualifiers(unsigned mask) {
315 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
316 Mask |= mask;
317 }
318
319 bool hasUnaligned() const { return Mask & UMask; }
320 void setUnaligned(bool flag) {
321 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
322 }
323 void removeUnaligned() { Mask &= ~UMask; }
324 void addUnaligned() { Mask |= UMask; }
325
326 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
327 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
328 void setObjCGCAttr(GC type) {
329 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
330 }
331 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
332 void addObjCGCAttr(GC type) {
333 assert(type);
334 setObjCGCAttr(type);
335 }
336 Qualifiers withoutObjCGCAttr() const {
337 Qualifiers qs = *this;
338 qs.removeObjCGCAttr();
339 return qs;
340 }
341 Qualifiers withoutObjCLifetime() const {
342 Qualifiers qs = *this;
343 qs.removeObjCLifetime();
344 return qs;
345 }
346 Qualifiers withoutAddressSpace() const {
347 Qualifiers qs = *this;
348 qs.removeAddressSpace();
349 return qs;
350 }
351
352 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
353 ObjCLifetime getObjCLifetime() const {
354 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
355 }
356 void setObjCLifetime(ObjCLifetime type) {
357 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
358 }
359 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
360 void addObjCLifetime(ObjCLifetime type) {
361 assert(type);
362 assert(!hasObjCLifetime());
363 Mask |= (type << LifetimeShift);
364 }
365
366 /// True if the lifetime is neither None or ExplicitNone.
367 bool hasNonTrivialObjCLifetime() const {
368 ObjCLifetime lifetime = getObjCLifetime();
369 return (lifetime > OCL_ExplicitNone);
370 }
371
372 /// True if the lifetime is either strong or weak.
373 bool hasStrongOrWeakObjCLifetime() const {
374 ObjCLifetime lifetime = getObjCLifetime();
375 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
376 }
377
378 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
379 LangAS getAddressSpace() const {
380 return static_cast<LangAS>(Mask >> AddressSpaceShift);
381 }
382 bool hasTargetSpecificAddressSpace() const {
383 return isTargetAddressSpace(AS: getAddressSpace());
384 }
385 /// Get the address space attribute value to be printed by diagnostics.
386 unsigned getAddressSpaceAttributePrintValue() const {
387 auto Addr = getAddressSpace();
388 // This function is not supposed to be used with language specific
389 // address spaces. If that happens, the diagnostic message should consider
390 // printing the QualType instead of the address space value.
391 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
392 if (Addr != LangAS::Default)
393 return toTargetAddressSpace(AS: Addr);
394 // TODO: The diagnostic messages where Addr may be 0 should be fixed
395 // since it cannot differentiate the situation where 0 denotes the default
396 // address space or user specified __attribute__((address_space(0))).
397 return 0;
398 }
399 void setAddressSpace(LangAS space) {
400 assert((unsigned)space <= MaxAddressSpace);
401 Mask = (Mask & ~AddressSpaceMask)
402 | (((uint32_t) space) << AddressSpaceShift);
403 }
404 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
405 void addAddressSpace(LangAS space) {
406 assert(space != LangAS::Default);
407 setAddressSpace(space);
408 }
409
410 // Fast qualifiers are those that can be allocated directly
411 // on a QualType object.
412 bool hasFastQualifiers() const { return getFastQualifiers(); }
413 unsigned getFastQualifiers() const { return Mask & FastMask; }
414 void setFastQualifiers(unsigned mask) {
415 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
416 Mask = (Mask & ~FastMask) | mask;
417 }
418 void removeFastQualifiers(unsigned mask) {
419 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
420 Mask &= ~mask;
421 }
422 void removeFastQualifiers() {
423 removeFastQualifiers(mask: FastMask);
424 }
425 void addFastQualifiers(unsigned mask) {
426 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
427 Mask |= mask;
428 }
429
430 /// Return true if the set contains any qualifiers which require an ExtQuals
431 /// node to be allocated.
432 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
433 Qualifiers getNonFastQualifiers() const {
434 Qualifiers Quals = *this;
435 Quals.setFastQualifiers(0);
436 return Quals;
437 }
438
439 /// Return true if the set contains any qualifiers.
440 bool hasQualifiers() const { return Mask; }
441 bool empty() const { return !Mask; }
442
443 /// Add the qualifiers from the given set to this set.
444 void addQualifiers(Qualifiers Q) {
445 // If the other set doesn't have any non-boolean qualifiers, just
446 // bit-or it in.
447 if (!(Q.Mask & ~CVRMask))
448 Mask |= Q.Mask;
449 else {
450 Mask |= (Q.Mask & CVRMask);
451 if (Q.hasAddressSpace())
452 addAddressSpace(space: Q.getAddressSpace());
453 if (Q.hasObjCGCAttr())
454 addObjCGCAttr(type: Q.getObjCGCAttr());
455 if (Q.hasObjCLifetime())
456 addObjCLifetime(type: Q.getObjCLifetime());
457 }
458 }
459
460 /// Remove the qualifiers from the given set from this set.
461 void removeQualifiers(Qualifiers Q) {
462 // If the other set doesn't have any non-boolean qualifiers, just
463 // bit-and the inverse in.
464 if (!(Q.Mask & ~CVRMask))
465 Mask &= ~Q.Mask;
466 else {
467 Mask &= ~(Q.Mask & CVRMask);
468 if (getObjCGCAttr() == Q.getObjCGCAttr())
469 removeObjCGCAttr();
470 if (getObjCLifetime() == Q.getObjCLifetime())
471 removeObjCLifetime();
472 if (getAddressSpace() == Q.getAddressSpace())
473 removeAddressSpace();
474 }
475 }
476
477 /// Add the qualifiers from the given set to this set, given that
478 /// they don't conflict.
479 void addConsistentQualifiers(Qualifiers qs) {
480 assert(getAddressSpace() == qs.getAddressSpace() ||
481 !hasAddressSpace() || !qs.hasAddressSpace());
482 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
483 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
484 assert(getObjCLifetime() == qs.getObjCLifetime() ||
485 !hasObjCLifetime() || !qs.hasObjCLifetime());
486 Mask |= qs.Mask;
487 }
488
489 /// Returns true if address space A is equal to or a superset of B.
490 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
491 /// overlapping address spaces.
492 /// CL1.1 or CL1.2:
493 /// every address space is a superset of itself.
494 /// CL2.0 adds:
495 /// __generic is a superset of any address space except for __constant.
496 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
497 // Address spaces must match exactly.
498 return A == B ||
499 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
500 // for __constant can be used as __generic.
501 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
502 // We also define global_device and global_host address spaces,
503 // to distinguish global pointers allocated on host from pointers
504 // allocated on device, which are a subset of __global.
505 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
506 B == LangAS::opencl_global_host)) ||
507 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
508 B == LangAS::sycl_global_host)) ||
509 // Consider pointer size address spaces to be equivalent to default.
510 ((isPtrSizeAddressSpace(AS: A) || A == LangAS::Default) &&
511 (isPtrSizeAddressSpace(AS: B) || B == LangAS::Default)) ||
512 // Default is a superset of SYCL address spaces.
513 (A == LangAS::Default &&
514 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
515 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
516 B == LangAS::sycl_global_host)) ||
517 // In HIP device compilation, any cuda address space is allowed
518 // to implicitly cast into the default address space.
519 (A == LangAS::Default &&
520 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
521 B == LangAS::cuda_shared));
522 }
523
524 /// Returns true if the address space in these qualifiers is equal to or
525 /// a superset of the address space in the argument qualifiers.
526 bool isAddressSpaceSupersetOf(Qualifiers other) const {
527 return isAddressSpaceSupersetOf(A: getAddressSpace(), B: other.getAddressSpace());
528 }
529
530 /// Determines if these qualifiers compatibly include another set.
531 /// Generally this answers the question of whether an object with the other
532 /// qualifiers can be safely used as an object with these qualifiers.
533 bool compatiblyIncludes(Qualifiers other) const {
534 return isAddressSpaceSupersetOf(other) &&
535 // ObjC GC qualifiers can match, be added, or be removed, but can't
536 // be changed.
537 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
538 !other.hasObjCGCAttr()) &&
539 // ObjC lifetime qualifiers must match exactly.
540 getObjCLifetime() == other.getObjCLifetime() &&
541 // CVR qualifiers may subset.
542 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
543 // U qualifier may superset.
544 (!other.hasUnaligned() || hasUnaligned());
545 }
546
547 /// Determines if these qualifiers compatibly include another set of
548 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
549 ///
550 /// One set of Objective-C lifetime qualifiers compatibly includes the other
551 /// if the lifetime qualifiers match, or if both are non-__weak and the
552 /// including set also contains the 'const' qualifier, or both are non-__weak
553 /// and one is None (which can only happen in non-ARC modes).
554 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
555 if (getObjCLifetime() == other.getObjCLifetime())
556 return true;
557
558 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
559 return false;
560
561 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
562 return true;
563
564 return hasConst();
565 }
566
567 /// Determine whether this set of qualifiers is a strict superset of
568 /// another set of qualifiers, not considering qualifier compatibility.
569 bool isStrictSupersetOf(Qualifiers Other) const;
570
571 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
572 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
573
574 explicit operator bool() const { return hasQualifiers(); }
575
576 Qualifiers &operator+=(Qualifiers R) {
577 addQualifiers(Q: R);
578 return *this;
579 }
580
581 // Union two qualifier sets. If an enumerated qualifier appears
582 // in both sets, use the one from the right.
583 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
584 L += R;
585 return L;
586 }
587
588 Qualifiers &operator-=(Qualifiers R) {
589 removeQualifiers(Q: R);
590 return *this;
591 }
592
593 /// Compute the difference between two qualifier sets.
594 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
595 L -= R;
596 return L;
597 }
598
599 std::string getAsString() const;
600 std::string getAsString(const PrintingPolicy &Policy) const;
601
602 static std::string getAddrSpaceAsString(LangAS AS);
603
604 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
605 void print(raw_ostream &OS, const PrintingPolicy &Policy,
606 bool appendSpaceIfNonEmpty = false) const;
607
608 void Profile(llvm::FoldingSetNodeID &ID) const {
609 ID.AddInteger(I: Mask);
610 }
611
612private:
613 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
614 // |C R V|U|GCAttr|Lifetime|AddressSpace|
615 uint32_t Mask = 0;
616
617 static const uint32_t UMask = 0x8;
618 static const uint32_t UShift = 3;
619 static const uint32_t GCAttrMask = 0x30;
620 static const uint32_t GCAttrShift = 4;
621 static const uint32_t LifetimeMask = 0x1C0;
622 static const uint32_t LifetimeShift = 6;
623 static const uint32_t AddressSpaceMask =
624 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
625 static const uint32_t AddressSpaceShift = 9;
626};
627
628class QualifiersAndAtomic {
629 Qualifiers Quals;
630 bool HasAtomic;
631
632public:
633 QualifiersAndAtomic() : HasAtomic(false) {}
634 QualifiersAndAtomic(Qualifiers Quals, bool HasAtomic)
635 : Quals(Quals), HasAtomic(HasAtomic) {}
636
637 operator Qualifiers() const { return Quals; }
638
639 bool hasVolatile() const { return Quals.hasVolatile(); }
640 bool hasConst() const { return Quals.hasConst(); }
641 bool hasRestrict() const { return Quals.hasRestrict(); }
642 bool hasAtomic() const { return HasAtomic; }
643
644 void addVolatile() { Quals.addVolatile(); }
645 void addConst() { Quals.addConst(); }
646 void addRestrict() { Quals.addRestrict(); }
647 void addAtomic() { HasAtomic = true; }
648
649 void removeVolatile() { Quals.removeVolatile(); }
650 void removeConst() { Quals.removeConst(); }
651 void removeRestrict() { Quals.removeRestrict(); }
652 void removeAtomic() { HasAtomic = false; }
653
654 QualifiersAndAtomic withVolatile() {
655 return {Quals.withVolatile(), HasAtomic};
656 }
657 QualifiersAndAtomic withConst() { return {Quals.withConst(), HasAtomic}; }
658 QualifiersAndAtomic withRestrict() {
659 return {Quals.withRestrict(), HasAtomic};
660 }
661 QualifiersAndAtomic withAtomic() { return {Quals, true}; }
662
663 QualifiersAndAtomic &operator+=(Qualifiers RHS) {
664 Quals += RHS;
665 return *this;
666 }
667};
668
669/// A std::pair-like structure for storing a qualified type split
670/// into its local qualifiers and its locally-unqualified type.
671struct SplitQualType {
672 /// The locally-unqualified type.
673 const Type *Ty = nullptr;
674
675 /// The local qualifiers.
676 Qualifiers Quals;
677
678 SplitQualType() = default;
679 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
680
681 SplitQualType getSingleStepDesugaredType() const; // end of this file
682
683 // Make std::tie work.
684 std::pair<const Type *,Qualifiers> asPair() const {
685 return std::pair<const Type *, Qualifiers>(Ty, Quals);
686 }
687
688 friend bool operator==(SplitQualType a, SplitQualType b) {
689 return a.Ty == b.Ty && a.Quals == b.Quals;
690 }
691 friend bool operator!=(SplitQualType a, SplitQualType b) {
692 return a.Ty != b.Ty || a.Quals != b.Quals;
693 }
694};
695
696/// The kind of type we are substituting Objective-C type arguments into.
697///
698/// The kind of substitution affects the replacement of type parameters when
699/// no concrete type information is provided, e.g., when dealing with an
700/// unspecialized type.
701enum class ObjCSubstitutionContext {
702 /// An ordinary type.
703 Ordinary,
704
705 /// The result type of a method or function.
706 Result,
707
708 /// The parameter type of a method or function.
709 Parameter,
710
711 /// The type of a property.
712 Property,
713
714 /// The superclass of a type.
715 Superclass,
716};
717
718/// The kind of 'typeof' expression we're after.
719enum class TypeOfKind : uint8_t {
720 Qualified,
721 Unqualified,
722};
723
724/// A (possibly-)qualified type.
725///
726/// For efficiency, we don't store CV-qualified types as nodes on their
727/// own: instead each reference to a type stores the qualifiers. This
728/// greatly reduces the number of nodes we need to allocate for types (for
729/// example we only need one for 'int', 'const int', 'volatile int',
730/// 'const volatile int', etc).
731///
732/// As an added efficiency bonus, instead of making this a pair, we
733/// just store the two bits we care about in the low bits of the
734/// pointer. To handle the packing/unpacking, we make QualType be a
735/// simple wrapper class that acts like a smart pointer. A third bit
736/// indicates whether there are extended qualifiers present, in which
737/// case the pointer points to a special structure.
738class QualType {
739 friend class QualifierCollector;
740
741 // Thankfully, these are efficiently composable.
742 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
743 Qualifiers::FastWidth> Value;
744
745 const ExtQuals *getExtQualsUnsafe() const {
746 return Value.getPointer().get<const ExtQuals*>();
747 }
748
749 const Type *getTypePtrUnsafe() const {
750 return Value.getPointer().get<const Type*>();
751 }
752
753 const ExtQualsTypeCommonBase *getCommonPtr() const {
754 assert(!isNull() && "Cannot retrieve a NULL type pointer");
755 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
756 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
757 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
758 }
759
760public:
761 QualType() = default;
762 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
763 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
764
765 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
766 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
767
768 bool UseExcessPrecision(const ASTContext &Ctx);
769
770 /// Retrieves a pointer to the underlying (unqualified) type.
771 ///
772 /// This function requires that the type not be NULL. If the type might be
773 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
774 const Type *getTypePtr() const;
775
776 const Type *getTypePtrOrNull() const;
777
778 /// Retrieves a pointer to the name of the base type.
779 const IdentifierInfo *getBaseTypeIdentifier() const;
780
781 /// Divides a QualType into its unqualified type and a set of local
782 /// qualifiers.
783 SplitQualType split() const;
784
785 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
786
787 static QualType getFromOpaquePtr(const void *Ptr) {
788 QualType T;
789 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
790 return T;
791 }
792
793 const Type &operator*() const {
794 return *getTypePtr();
795 }
796
797 const Type *operator->() const {
798 return getTypePtr();
799 }
800
801 bool isCanonical() const;
802 bool isCanonicalAsParam() const;
803
804 /// Return true if this QualType doesn't point to a type yet.
805 bool isNull() const {
806 return Value.getPointer().isNull();
807 }
808
809 // Determines if a type can form `T&`.
810 bool isReferenceable() const;
811
812 /// Determine whether this particular QualType instance has the
813 /// "const" qualifier set, without looking through typedefs that may have
814 /// added "const" at a different level.
815 bool isLocalConstQualified() const {
816 return (getLocalFastQualifiers() & Qualifiers::Const);
817 }
818
819 /// Determine whether this type is const-qualified.
820 bool isConstQualified() const;
821
822 enum class NonConstantStorageReason {
823 MutableField,
824 NonConstNonReferenceType,
825 NonTrivialCtor,
826 NonTrivialDtor,
827 };
828 /// Determine whether instances of this type can be placed in immutable
829 /// storage.
830 /// If ExcludeCtor is true, the duration when the object's constructor runs
831 /// will not be considered. The caller will need to verify that the object is
832 /// not written to during its construction. ExcludeDtor works similarly.
833 std::optional<NonConstantStorageReason>
834 isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
835 bool ExcludeDtor);
836
837 bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
838 bool ExcludeDtor) {
839 return !isNonConstantStorage(Ctx, ExcludeCtor, ExcludeDtor);
840 }
841
842 /// Determine whether this particular QualType instance has the
843 /// "restrict" qualifier set, without looking through typedefs that may have
844 /// added "restrict" at a different level.
845 bool isLocalRestrictQualified() const {
846 return (getLocalFastQualifiers() & Qualifiers::Restrict);
847 }
848
849 /// Determine whether this type is restrict-qualified.
850 bool isRestrictQualified() const;
851
852 /// Determine whether this particular QualType instance has the
853 /// "volatile" qualifier set, without looking through typedefs that may have
854 /// added "volatile" at a different level.
855 bool isLocalVolatileQualified() const {
856 return (getLocalFastQualifiers() & Qualifiers::Volatile);
857 }
858
859 /// Determine whether this type is volatile-qualified.
860 bool isVolatileQualified() const;
861
862 /// Determine whether this particular QualType instance has any
863 /// qualifiers, without looking through any typedefs that might add
864 /// qualifiers at a different level.
865 bool hasLocalQualifiers() const {
866 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
867 }
868
869 /// Determine whether this type has any qualifiers.
870 bool hasQualifiers() const;
871
872 /// Determine whether this particular QualType instance has any
873 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
874 /// instance.
875 bool hasLocalNonFastQualifiers() const {
876 return Value.getPointer().is<const ExtQuals*>();
877 }
878
879 /// Retrieve the set of qualifiers local to this particular QualType
880 /// instance, not including any qualifiers acquired through typedefs or
881 /// other sugar.
882 Qualifiers getLocalQualifiers() const;
883
884 /// Retrieve the set of qualifiers applied to this type.
885 Qualifiers getQualifiers() const;
886
887 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
888 /// local to this particular QualType instance, not including any qualifiers
889 /// acquired through typedefs or other sugar.
890 unsigned getLocalCVRQualifiers() const {
891 return getLocalFastQualifiers();
892 }
893
894 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
895 /// applied to this type.
896 unsigned getCVRQualifiers() const;
897
898 bool isConstant(const ASTContext& Ctx) const {
899 return QualType::isConstant(T: *this, Ctx);
900 }
901
902 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
903 bool isPODType(const ASTContext &Context) const;
904
905 /// Return true if this is a POD type according to the rules of the C++98
906 /// standard, regardless of the current compilation's language.
907 bool isCXX98PODType(const ASTContext &Context) const;
908
909 /// Return true if this is a POD type according to the more relaxed rules
910 /// of the C++11 standard, regardless of the current compilation's language.
911 /// (C++0x [basic.types]p9). Note that, unlike
912 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
913 bool isCXX11PODType(const ASTContext &Context) const;
914
915 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
916 bool isTrivialType(const ASTContext &Context) const;
917
918 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
919 bool isTriviallyCopyableType(const ASTContext &Context) const;
920
921 /// Return true if this is a trivially copyable type
922 bool isTriviallyCopyConstructibleType(const ASTContext &Context) const;
923
924 /// Return true if this is a trivially relocatable type.
925 bool isTriviallyRelocatableType(const ASTContext &Context) const;
926
927 /// Return true if this is a trivially equality comparable type.
928 bool isTriviallyEqualityComparableType(const ASTContext &Context) const;
929
930 /// Returns true if it is a class and it might be dynamic.
931 bool mayBeDynamicClass() const;
932
933 /// Returns true if it is not a class or if the class might not be dynamic.
934 bool mayBeNotDynamicClass() const;
935
936 /// Returns true if it is a WebAssembly Reference Type.
937 bool isWebAssemblyReferenceType() const;
938
939 /// Returns true if it is a WebAssembly Externref Type.
940 bool isWebAssemblyExternrefType() const;
941
942 /// Returns true if it is a WebAssembly Funcref Type.
943 bool isWebAssemblyFuncrefType() const;
944
945 // Don't promise in the API that anything besides 'const' can be
946 // easily added.
947
948 /// Add the `const` type qualifier to this QualType.
949 void addConst() {
950 addFastQualifiers(TQs: Qualifiers::Const);
951 }
952 QualType withConst() const {
953 return withFastQualifiers(TQs: Qualifiers::Const);
954 }
955
956 /// Add the `volatile` type qualifier to this QualType.
957 void addVolatile() {
958 addFastQualifiers(TQs: Qualifiers::Volatile);
959 }
960 QualType withVolatile() const {
961 return withFastQualifiers(TQs: Qualifiers::Volatile);
962 }
963
964 /// Add the `restrict` qualifier to this QualType.
965 void addRestrict() {
966 addFastQualifiers(TQs: Qualifiers::Restrict);
967 }
968 QualType withRestrict() const {
969 return withFastQualifiers(TQs: Qualifiers::Restrict);
970 }
971
972 QualType withCVRQualifiers(unsigned CVR) const {
973 return withFastQualifiers(TQs: CVR);
974 }
975
976 void addFastQualifiers(unsigned TQs) {
977 assert(!(TQs & ~Qualifiers::FastMask)
978 && "non-fast qualifier bits set in mask!");
979 Value.setInt(Value.getInt() | TQs);
980 }
981
982 void removeLocalConst();
983 void removeLocalVolatile();
984 void removeLocalRestrict();
985
986 void removeLocalFastQualifiers() { Value.setInt(0); }
987 void removeLocalFastQualifiers(unsigned Mask) {
988 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
989 Value.setInt(Value.getInt() & ~Mask);
990 }
991
992 // Creates a type with the given qualifiers in addition to any
993 // qualifiers already on this type.
994 QualType withFastQualifiers(unsigned TQs) const {
995 QualType T = *this;
996 T.addFastQualifiers(TQs);
997 return T;
998 }
999
1000 // Creates a type with exactly the given fast qualifiers, removing
1001 // any existing fast qualifiers.
1002 QualType withExactLocalFastQualifiers(unsigned TQs) const {
1003 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
1004 }
1005
1006 // Removes fast qualifiers, but leaves any extended qualifiers in place.
1007 QualType withoutLocalFastQualifiers() const {
1008 QualType T = *this;
1009 T.removeLocalFastQualifiers();
1010 return T;
1011 }
1012
1013 QualType getCanonicalType() const;
1014
1015 /// Return this type with all of the instance-specific qualifiers
1016 /// removed, but without removing any qualifiers that may have been applied
1017 /// through typedefs.
1018 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
1019
1020 /// Retrieve the unqualified variant of the given type,
1021 /// removing as little sugar as possible.
1022 ///
1023 /// This routine looks through various kinds of sugar to find the
1024 /// least-desugared type that is unqualified. For example, given:
1025 ///
1026 /// \code
1027 /// typedef int Integer;
1028 /// typedef const Integer CInteger;
1029 /// typedef CInteger DifferenceType;
1030 /// \endcode
1031 ///
1032 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
1033 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
1034 ///
1035 /// The resulting type might still be qualified if it's sugar for an array
1036 /// type. To strip qualifiers even from within a sugared array type, use
1037 /// ASTContext::getUnqualifiedArrayType.
1038 ///
1039 /// Note: In C, the _Atomic qualifier is special (see C23 6.2.5p32 for
1040 /// details), and it is not stripped by this function. Use
1041 /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic.
1042 inline QualType getUnqualifiedType() const;
1043
1044 /// Retrieve the unqualified variant of the given type, removing as little
1045 /// sugar as possible.
1046 ///
1047 /// Like getUnqualifiedType(), but also returns the set of
1048 /// qualifiers that were built up.
1049 ///
1050 /// The resulting type might still be qualified if it's sugar for an array
1051 /// type. To strip qualifiers even from within a sugared array type, use
1052 /// ASTContext::getUnqualifiedArrayType.
1053 inline SplitQualType getSplitUnqualifiedType() const;
1054
1055 /// Determine whether this type is more qualified than the other
1056 /// given type, requiring exact equality for non-CVR qualifiers.
1057 bool isMoreQualifiedThan(QualType Other) const;
1058
1059 /// Determine whether this type is at least as qualified as the other
1060 /// given type, requiring exact equality for non-CVR qualifiers.
1061 bool isAtLeastAsQualifiedAs(QualType Other) const;
1062
1063 QualType getNonReferenceType() const;
1064
1065 /// Determine the type of a (typically non-lvalue) expression with the
1066 /// specified result type.
1067 ///
1068 /// This routine should be used for expressions for which the return type is
1069 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
1070 /// an lvalue. It removes a top-level reference (since there are no
1071 /// expressions of reference type) and deletes top-level cvr-qualifiers
1072 /// from non-class types (in C++) or all types (in C).
1073 QualType getNonLValueExprType(const ASTContext &Context) const;
1074
1075 /// Remove an outer pack expansion type (if any) from this type. Used as part
1076 /// of converting the type of a declaration to the type of an expression that
1077 /// references that expression. It's meaningless for an expression to have a
1078 /// pack expansion type.
1079 QualType getNonPackExpansionType() const;
1080
1081 /// Return the specified type with any "sugar" removed from
1082 /// the type. This takes off typedefs, typeof's etc. If the outer level of
1083 /// the type is already concrete, it returns it unmodified. This is similar
1084 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
1085 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
1086 /// concrete.
1087 ///
1088 /// Qualifiers are left in place.
1089 QualType getDesugaredType(const ASTContext &Context) const {
1090 return getDesugaredType(T: *this, Context);
1091 }
1092
1093 SplitQualType getSplitDesugaredType() const {
1094 return getSplitDesugaredType(T: *this);
1095 }
1096
1097 /// Return the specified type with one level of "sugar" removed from
1098 /// the type.
1099 ///
1100 /// This routine takes off the first typedef, typeof, etc. If the outer level
1101 /// of the type is already concrete, it returns it unmodified.
1102 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
1103 return getSingleStepDesugaredTypeImpl(type: *this, C: Context);
1104 }
1105
1106 /// Returns the specified type after dropping any
1107 /// outer-level parentheses.
1108 QualType IgnoreParens() const {
1109 if (isa<ParenType>(*this))
1110 return QualType::IgnoreParens(T: *this);
1111 return *this;
1112 }
1113
1114 /// Indicate whether the specified types and qualifiers are identical.
1115 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1116 return LHS.Value == RHS.Value;
1117 }
1118 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1119 return LHS.Value != RHS.Value;
1120 }
1121 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1122 return LHS.Value < RHS.Value;
1123 }
1124
1125 static std::string getAsString(SplitQualType split,
1126 const PrintingPolicy &Policy) {
1127 return getAsString(ty: split.Ty, qs: split.Quals, Policy);
1128 }
1129 static std::string getAsString(const Type *ty, Qualifiers qs,
1130 const PrintingPolicy &Policy);
1131
1132 std::string getAsString() const;
1133 std::string getAsString(const PrintingPolicy &Policy) const;
1134
1135 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1136 const Twine &PlaceHolder = Twine(),
1137 unsigned Indentation = 0) const;
1138
1139 static void print(SplitQualType split, raw_ostream &OS,
1140 const PrintingPolicy &policy, const Twine &PlaceHolder,
1141 unsigned Indentation = 0) {
1142 return print(ty: split.Ty, qs: split.Quals, OS, policy, PlaceHolder, Indentation);
1143 }
1144
1145 static void print(const Type *ty, Qualifiers qs,
1146 raw_ostream &OS, const PrintingPolicy &policy,
1147 const Twine &PlaceHolder,
1148 unsigned Indentation = 0);
1149
1150 void getAsStringInternal(std::string &Str,
1151 const PrintingPolicy &Policy) const;
1152
1153 static void getAsStringInternal(SplitQualType split, std::string &out,
1154 const PrintingPolicy &policy) {
1155 return getAsStringInternal(ty: split.Ty, qs: split.Quals, out, policy);
1156 }
1157
1158 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1159 std::string &out,
1160 const PrintingPolicy &policy);
1161
1162 class StreamedQualTypeHelper {
1163 const QualType &T;
1164 const PrintingPolicy &Policy;
1165 const Twine &PlaceHolder;
1166 unsigned Indentation;
1167
1168 public:
1169 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1170 const Twine &PlaceHolder, unsigned Indentation)
1171 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1172 Indentation(Indentation) {}
1173
1174 friend raw_ostream &operator<<(raw_ostream &OS,
1175 const StreamedQualTypeHelper &SQT) {
1176 SQT.T.print(OS, Policy: SQT.Policy, PlaceHolder: SQT.PlaceHolder, Indentation: SQT.Indentation);
1177 return OS;
1178 }
1179 };
1180
1181 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1182 const Twine &PlaceHolder = Twine(),
1183 unsigned Indentation = 0) const {
1184 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1185 }
1186
1187 void dump(const char *s) const;
1188 void dump() const;
1189 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1190
1191 void Profile(llvm::FoldingSetNodeID &ID) const {
1192 ID.AddPointer(Ptr: getAsOpaquePtr());
1193 }
1194
1195 /// Check if this type has any address space qualifier.
1196 inline bool hasAddressSpace() const;
1197
1198 /// Return the address space of this type.
1199 inline LangAS getAddressSpace() const;
1200
1201 /// Returns true if address space qualifiers overlap with T address space
1202 /// qualifiers.
1203 /// OpenCL C defines conversion rules for pointers to different address spaces
1204 /// and notion of overlapping address spaces.
1205 /// CL1.1 or CL1.2:
1206 /// address spaces overlap iff they are they same.
1207 /// OpenCL C v2.0 s6.5.5 adds:
1208 /// __generic overlaps with any address space except for __constant.
1209 bool isAddressSpaceOverlapping(QualType T) const {
1210 Qualifiers Q = getQualifiers();
1211 Qualifiers TQ = T.getQualifiers();
1212 // Address spaces overlap if at least one of them is a superset of another
1213 return Q.isAddressSpaceSupersetOf(other: TQ) || TQ.isAddressSpaceSupersetOf(other: Q);
1214 }
1215
1216 /// Returns gc attribute of this type.
1217 inline Qualifiers::GC getObjCGCAttr() const;
1218
1219 /// true when Type is objc's weak.
1220 bool isObjCGCWeak() const {
1221 return getObjCGCAttr() == Qualifiers::Weak;
1222 }
1223
1224 /// true when Type is objc's strong.
1225 bool isObjCGCStrong() const {
1226 return getObjCGCAttr() == Qualifiers::Strong;
1227 }
1228
1229 /// Returns lifetime attribute of this type.
1230 Qualifiers::ObjCLifetime getObjCLifetime() const {
1231 return getQualifiers().getObjCLifetime();
1232 }
1233
1234 bool hasNonTrivialObjCLifetime() const {
1235 return getQualifiers().hasNonTrivialObjCLifetime();
1236 }
1237
1238 bool hasStrongOrWeakObjCLifetime() const {
1239 return getQualifiers().hasStrongOrWeakObjCLifetime();
1240 }
1241
1242 // true when Type is objc's weak and weak is enabled but ARC isn't.
1243 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1244
1245 enum PrimitiveDefaultInitializeKind {
1246 /// The type does not fall into any of the following categories. Note that
1247 /// this case is zero-valued so that values of this enum can be used as a
1248 /// boolean condition for non-triviality.
1249 PDIK_Trivial,
1250
1251 /// The type is an Objective-C retainable pointer type that is qualified
1252 /// with the ARC __strong qualifier.
1253 PDIK_ARCStrong,
1254
1255 /// The type is an Objective-C retainable pointer type that is qualified
1256 /// with the ARC __weak qualifier.
1257 PDIK_ARCWeak,
1258
1259 /// The type is a struct containing a field whose type is not PCK_Trivial.
1260 PDIK_Struct
1261 };
1262
1263 /// Functions to query basic properties of non-trivial C struct types.
1264
1265 /// Check if this is a non-trivial type that would cause a C struct
1266 /// transitively containing this type to be non-trivial to default initialize
1267 /// and return the kind.
1268 PrimitiveDefaultInitializeKind
1269 isNonTrivialToPrimitiveDefaultInitialize() const;
1270
1271 enum PrimitiveCopyKind {
1272 /// The type does not fall into any of the following categories. Note that
1273 /// this case is zero-valued so that values of this enum can be used as a
1274 /// boolean condition for non-triviality.
1275 PCK_Trivial,
1276
1277 /// The type would be trivial except that it is volatile-qualified. Types
1278 /// that fall into one of the other non-trivial cases may additionally be
1279 /// volatile-qualified.
1280 PCK_VolatileTrivial,
1281
1282 /// The type is an Objective-C retainable pointer type that is qualified
1283 /// with the ARC __strong qualifier.
1284 PCK_ARCStrong,
1285
1286 /// The type is an Objective-C retainable pointer type that is qualified
1287 /// with the ARC __weak qualifier.
1288 PCK_ARCWeak,
1289
1290 /// The type is a struct containing a field whose type is neither
1291 /// PCK_Trivial nor PCK_VolatileTrivial.
1292 /// Note that a C++ struct type does not necessarily match this; C++ copying
1293 /// semantics are too complex to express here, in part because they depend
1294 /// on the exact constructor or assignment operator that is chosen by
1295 /// overload resolution to do the copy.
1296 PCK_Struct
1297 };
1298
1299 /// Check if this is a non-trivial type that would cause a C struct
1300 /// transitively containing this type to be non-trivial to copy and return the
1301 /// kind.
1302 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1303
1304 /// Check if this is a non-trivial type that would cause a C struct
1305 /// transitively containing this type to be non-trivial to destructively
1306 /// move and return the kind. Destructive move in this context is a C++-style
1307 /// move in which the source object is placed in a valid but unspecified state
1308 /// after it is moved, as opposed to a truly destructive move in which the
1309 /// source object is placed in an uninitialized state.
1310 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1311
1312 enum DestructionKind {
1313 DK_none,
1314 DK_cxx_destructor,
1315 DK_objc_strong_lifetime,
1316 DK_objc_weak_lifetime,
1317 DK_nontrivial_c_struct
1318 };
1319
1320 /// Returns a nonzero value if objects of this type require
1321 /// non-trivial work to clean up after. Non-zero because it's
1322 /// conceivable that qualifiers (objc_gc(weak)?) could make
1323 /// something require destruction.
1324 DestructionKind isDestructedType() const {
1325 return isDestructedTypeImpl(type: *this);
1326 }
1327
1328 /// Check if this is or contains a C union that is non-trivial to
1329 /// default-initialize, which is a union that has a member that is non-trivial
1330 /// to default-initialize. If this returns true,
1331 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1332 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1333
1334 /// Check if this is or contains a C union that is non-trivial to destruct,
1335 /// which is a union that has a member that is non-trivial to destruct. If
1336 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1337 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1338
1339 /// Check if this is or contains a C union that is non-trivial to copy, which
1340 /// is a union that has a member that is non-trivial to copy. If this returns
1341 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1342 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1343
1344 /// Determine whether expressions of the given type are forbidden
1345 /// from being lvalues in C.
1346 ///
1347 /// The expression types that are forbidden to be lvalues are:
1348 /// - 'void', but not qualified void
1349 /// - function types
1350 ///
1351 /// The exact rule here is C99 6.3.2.1:
1352 /// An lvalue is an expression with an object type or an incomplete
1353 /// type other than void.
1354 bool isCForbiddenLValueType() const;
1355
1356 /// Substitute type arguments for the Objective-C type parameters used in the
1357 /// subject type.
1358 ///
1359 /// \param ctx ASTContext in which the type exists.
1360 ///
1361 /// \param typeArgs The type arguments that will be substituted for the
1362 /// Objective-C type parameters in the subject type, which are generally
1363 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1364 /// parameters will be replaced with their bounds or id/Class, as appropriate
1365 /// for the context.
1366 ///
1367 /// \param context The context in which the subject type was written.
1368 ///
1369 /// \returns the resulting type.
1370 QualType substObjCTypeArgs(ASTContext &ctx,
1371 ArrayRef<QualType> typeArgs,
1372 ObjCSubstitutionContext context) const;
1373
1374 /// Substitute type arguments from an object type for the Objective-C type
1375 /// parameters used in the subject type.
1376 ///
1377 /// This operation combines the computation of type arguments for
1378 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1379 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1380 /// callers that need to perform a single substitution in isolation.
1381 ///
1382 /// \param objectType The type of the object whose member type we're
1383 /// substituting into. For example, this might be the receiver of a message
1384 /// or the base of a property access.
1385 ///
1386 /// \param dc The declaration context from which the subject type was
1387 /// retrieved, which indicates (for example) which type parameters should
1388 /// be substituted.
1389 ///
1390 /// \param context The context in which the subject type was written.
1391 ///
1392 /// \returns the subject type after replacing all of the Objective-C type
1393 /// parameters with their corresponding arguments.
1394 QualType substObjCMemberType(QualType objectType,
1395 const DeclContext *dc,
1396 ObjCSubstitutionContext context) const;
1397
1398 /// Strip Objective-C "__kindof" types from the given type.
1399 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1400
1401 /// Remove all qualifiers including _Atomic.
1402 QualType getAtomicUnqualifiedType() const;
1403
1404private:
1405 // These methods are implemented in a separate translation unit;
1406 // "static"-ize them to avoid creating temporary QualTypes in the
1407 // caller.
1408 static bool isConstant(QualType T, const ASTContext& Ctx);
1409 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1410 static SplitQualType getSplitDesugaredType(QualType T);
1411 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1412 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1413 const ASTContext &C);
1414 static QualType IgnoreParens(QualType T);
1415 static DestructionKind isDestructedTypeImpl(QualType type);
1416
1417 /// Check if \param RD is or contains a non-trivial C union.
1418 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1419 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1420 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1421};
1422
1423raw_ostream &operator<<(raw_ostream &OS, QualType QT);
1424
1425} // namespace clang
1426
1427namespace llvm {
1428
1429/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1430/// to a specific Type class.
1431template<> struct simplify_type< ::clang::QualType> {
1432 using SimpleType = const ::clang::Type *;
1433
1434 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1435 return Val.getTypePtr();
1436 }
1437};
1438
1439// Teach SmallPtrSet that QualType is "basically a pointer".
1440template<>
1441struct PointerLikeTypeTraits<clang::QualType> {
1442 static inline void *getAsVoidPointer(clang::QualType P) {
1443 return P.getAsOpaquePtr();
1444 }
1445
1446 static inline clang::QualType getFromVoidPointer(void *P) {
1447 return clang::QualType::getFromOpaquePtr(Ptr: P);
1448 }
1449
1450 // Various qualifiers go in low bits.
1451 static constexpr int NumLowBitsAvailable = 0;
1452};
1453
1454} // namespace llvm
1455
1456namespace clang {
1457
1458/// Base class that is common to both the \c ExtQuals and \c Type
1459/// classes, which allows \c QualType to access the common fields between the
1460/// two.
1461class ExtQualsTypeCommonBase {
1462 friend class ExtQuals;
1463 friend class QualType;
1464 friend class Type;
1465
1466 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1467 /// a self-referential pointer (for \c Type).
1468 ///
1469 /// This pointer allows an efficient mapping from a QualType to its
1470 /// underlying type pointer.
1471 const Type *const BaseType;
1472
1473 /// The canonical type of this type. A QualType.
1474 QualType CanonicalType;
1475
1476 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1477 : BaseType(baseType), CanonicalType(canon) {}
1478};
1479
1480/// We can encode up to four bits in the low bits of a
1481/// type pointer, but there are many more type qualifiers that we want
1482/// to be able to apply to an arbitrary type. Therefore we have this
1483/// struct, intended to be heap-allocated and used by QualType to
1484/// store qualifiers.
1485///
1486/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1487/// in three low bits on the QualType pointer; a fourth bit records whether
1488/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1489/// Objective-C GC attributes) are much more rare.
1490class alignas(TypeAlignment) ExtQuals : public ExtQualsTypeCommonBase,
1491 public llvm::FoldingSetNode {
1492 // NOTE: changing the fast qualifiers should be straightforward as
1493 // long as you don't make 'const' non-fast.
1494 // 1. Qualifiers:
1495 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1496 // Fast qualifiers must occupy the low-order bits.
1497 // b) Update Qualifiers::FastWidth and FastMask.
1498 // 2. QualType:
1499 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1500 // b) Update remove{Volatile,Restrict}, defined near the end of
1501 // this header.
1502 // 3. ASTContext:
1503 // a) Update get{Volatile,Restrict}Type.
1504
1505 /// The immutable set of qualifiers applied by this node. Always contains
1506 /// extended qualifiers.
1507 Qualifiers Quals;
1508
1509 ExtQuals *this_() { return this; }
1510
1511public:
1512 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1513 : ExtQualsTypeCommonBase(baseType,
1514 canon.isNull() ? QualType(this_(), 0) : canon),
1515 Quals(quals) {
1516 assert(Quals.hasNonFastQualifiers()
1517 && "ExtQuals created with no fast qualifiers");
1518 assert(!Quals.hasFastQualifiers()
1519 && "ExtQuals created with fast qualifiers");
1520 }
1521
1522 Qualifiers getQualifiers() const { return Quals; }
1523
1524 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1525 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1526
1527 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1528 Qualifiers::ObjCLifetime getObjCLifetime() const {
1529 return Quals.getObjCLifetime();
1530 }
1531
1532 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1533 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1534
1535 const Type *getBaseType() const { return BaseType; }
1536
1537public:
1538 void Profile(llvm::FoldingSetNodeID &ID) const {
1539 Profile(ID, BaseType: getBaseType(), Quals);
1540 }
1541
1542 static void Profile(llvm::FoldingSetNodeID &ID,
1543 const Type *BaseType,
1544 Qualifiers Quals) {
1545 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1546 ID.AddPointer(Ptr: BaseType);
1547 Quals.Profile(ID);
1548 }
1549};
1550
1551/// The kind of C++11 ref-qualifier associated with a function type.
1552/// This determines whether a member function's "this" object can be an
1553/// lvalue, rvalue, or neither.
1554enum RefQualifierKind {
1555 /// No ref-qualifier was provided.
1556 RQ_None = 0,
1557
1558 /// An lvalue ref-qualifier was provided (\c &).
1559 RQ_LValue,
1560
1561 /// An rvalue ref-qualifier was provided (\c &&).
1562 RQ_RValue
1563};
1564
1565/// Which keyword(s) were used to create an AutoType.
1566enum class AutoTypeKeyword {
1567 /// auto
1568 Auto,
1569
1570 /// decltype(auto)
1571 DecltypeAuto,
1572
1573 /// __auto_type (GNU extension)
1574 GNUAutoType
1575};
1576
1577enum class ArraySizeModifier;
1578enum class ElaboratedTypeKeyword;
1579enum class VectorKind;
1580
1581/// The base class of the type hierarchy.
1582///
1583/// A central concept with types is that each type always has a canonical
1584/// type. A canonical type is the type with any typedef names stripped out
1585/// of it or the types it references. For example, consider:
1586///
1587/// typedef int foo;
1588/// typedef foo* bar;
1589/// 'int *' 'foo *' 'bar'
1590///
1591/// There will be a Type object created for 'int'. Since int is canonical, its
1592/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1593/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1594/// there is a PointerType that represents 'int*', which, like 'int', is
1595/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1596/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1597/// is also 'int*'.
1598///
1599/// Non-canonical types are useful for emitting diagnostics, without losing
1600/// information about typedefs being used. Canonical types are useful for type
1601/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1602/// about whether something has a particular form (e.g. is a function type),
1603/// because they implicitly, recursively, strip all typedefs out of a type.
1604///
1605/// Types, once created, are immutable.
1606///
1607class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
1608public:
1609 enum TypeClass {
1610#define TYPE(Class, Base) Class,
1611#define LAST_TYPE(Class) TypeLast = Class
1612#define ABSTRACT_TYPE(Class, Base)
1613#include "clang/AST/TypeNodes.inc"
1614 };
1615
1616private:
1617 /// Bitfields required by the Type class.
1618 class TypeBitfields {
1619 friend class Type;
1620 template <class T> friend class TypePropertyCache;
1621
1622 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1623 LLVM_PREFERRED_TYPE(TypeClass)
1624 unsigned TC : 8;
1625
1626 /// Store information on the type dependency.
1627 LLVM_PREFERRED_TYPE(TypeDependence)
1628 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1629
1630 /// True if the cache (i.e. the bitfields here starting with
1631 /// 'Cache') is valid.
1632 LLVM_PREFERRED_TYPE(bool)
1633 mutable unsigned CacheValid : 1;
1634
1635 /// Linkage of this type.
1636 LLVM_PREFERRED_TYPE(Linkage)
1637 mutable unsigned CachedLinkage : 3;
1638
1639 /// Whether this type involves and local or unnamed types.
1640 LLVM_PREFERRED_TYPE(bool)
1641 mutable unsigned CachedLocalOrUnnamed : 1;
1642
1643 /// Whether this type comes from an AST file.
1644 LLVM_PREFERRED_TYPE(bool)
1645 mutable unsigned FromAST : 1;
1646
1647 bool isCacheValid() const {
1648 return CacheValid;
1649 }
1650
1651 Linkage getLinkage() const {
1652 assert(isCacheValid() && "getting linkage from invalid cache");
1653 return static_cast<Linkage>(CachedLinkage);
1654 }
1655
1656 bool hasLocalOrUnnamedType() const {
1657 assert(isCacheValid() && "getting linkage from invalid cache");
1658 return CachedLocalOrUnnamed;
1659 }
1660 };
1661 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1662
1663protected:
1664 // These classes allow subclasses to somewhat cleanly pack bitfields
1665 // into Type.
1666
1667 class ArrayTypeBitfields {
1668 friend class ArrayType;
1669
1670 LLVM_PREFERRED_TYPE(TypeBitfields)
1671 unsigned : NumTypeBits;
1672
1673 /// CVR qualifiers from declarations like
1674 /// 'int X[static restrict 4]'. For function parameters only.
1675 LLVM_PREFERRED_TYPE(Qualifiers)
1676 unsigned IndexTypeQuals : 3;
1677
1678 /// Storage class qualifiers from declarations like
1679 /// 'int X[static restrict 4]'. For function parameters only.
1680 LLVM_PREFERRED_TYPE(ArraySizeModifier)
1681 unsigned SizeModifier : 3;
1682 };
1683 enum { NumArrayTypeBits = NumTypeBits + 6 };
1684
1685 class ConstantArrayTypeBitfields {
1686 friend class ConstantArrayType;
1687
1688 LLVM_PREFERRED_TYPE(ArrayTypeBitfields)
1689 unsigned : NumArrayTypeBits;
1690
1691 /// Whether we have a stored size expression.
1692 LLVM_PREFERRED_TYPE(bool)
1693 unsigned HasExternalSize : 1;
1694
1695 LLVM_PREFERRED_TYPE(unsigned)
1696 unsigned SizeWidth : 5;
1697 };
1698
1699 class BuiltinTypeBitfields {
1700 friend class BuiltinType;
1701
1702 LLVM_PREFERRED_TYPE(TypeBitfields)
1703 unsigned : NumTypeBits;
1704
1705 /// The kind (BuiltinType::Kind) of builtin type this is.
1706 static constexpr unsigned NumOfBuiltinTypeBits = 9;
1707 unsigned Kind : NumOfBuiltinTypeBits;
1708 };
1709
1710 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1711 /// Only common bits are stored here. Additional uncommon bits are stored
1712 /// in a trailing object after FunctionProtoType.
1713 class FunctionTypeBitfields {
1714 friend class FunctionProtoType;
1715 friend class FunctionType;
1716
1717 LLVM_PREFERRED_TYPE(TypeBitfields)
1718 unsigned : NumTypeBits;
1719
1720 /// Extra information which affects how the function is called, like
1721 /// regparm and the calling convention.
1722 LLVM_PREFERRED_TYPE(CallingConv)
1723 unsigned ExtInfo : 13;
1724
1725 /// The ref-qualifier associated with a \c FunctionProtoType.
1726 ///
1727 /// This is a value of type \c RefQualifierKind.
1728 LLVM_PREFERRED_TYPE(RefQualifierKind)
1729 unsigned RefQualifier : 2;
1730
1731 /// Used only by FunctionProtoType, put here to pack with the
1732 /// other bitfields.
1733 /// The qualifiers are part of FunctionProtoType because...
1734 ///
1735 /// C++ 8.3.5p4: The return type, the parameter type list and the
1736 /// cv-qualifier-seq, [...], are part of the function type.
1737 LLVM_PREFERRED_TYPE(Qualifiers)
1738 unsigned FastTypeQuals : Qualifiers::FastWidth;
1739 /// Whether this function has extended Qualifiers.
1740 LLVM_PREFERRED_TYPE(bool)
1741 unsigned HasExtQuals : 1;
1742
1743 /// The number of parameters this function has, not counting '...'.
1744 /// According to [implimits] 8 bits should be enough here but this is
1745 /// somewhat easy to exceed with metaprogramming and so we would like to
1746 /// keep NumParams as wide as reasonably possible.
1747 unsigned NumParams : 16;
1748
1749 /// The type of exception specification this function has.
1750 LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
1751 unsigned ExceptionSpecType : 4;
1752
1753 /// Whether this function has extended parameter information.
1754 LLVM_PREFERRED_TYPE(bool)
1755 unsigned HasExtParameterInfos : 1;
1756
1757 /// Whether this function has extra bitfields for the prototype.
1758 LLVM_PREFERRED_TYPE(bool)
1759 unsigned HasExtraBitfields : 1;
1760
1761 /// Whether the function is variadic.
1762 LLVM_PREFERRED_TYPE(bool)
1763 unsigned Variadic : 1;
1764
1765 /// Whether this function has a trailing return type.
1766 LLVM_PREFERRED_TYPE(bool)
1767 unsigned HasTrailingReturn : 1;
1768 };
1769
1770 class ObjCObjectTypeBitfields {
1771 friend class ObjCObjectType;
1772
1773 LLVM_PREFERRED_TYPE(TypeBitfields)
1774 unsigned : NumTypeBits;
1775
1776 /// The number of type arguments stored directly on this object type.
1777 unsigned NumTypeArgs : 7;
1778
1779 /// The number of protocols stored directly on this object type.
1780 unsigned NumProtocols : 6;
1781
1782 /// Whether this is a "kindof" type.
1783 LLVM_PREFERRED_TYPE(bool)
1784 unsigned IsKindOf : 1;
1785 };
1786
1787 class ReferenceTypeBitfields {
1788 friend class ReferenceType;
1789
1790 LLVM_PREFERRED_TYPE(TypeBitfields)
1791 unsigned : NumTypeBits;
1792
1793 /// True if the type was originally spelled with an lvalue sigil.
1794 /// This is never true of rvalue references but can also be false
1795 /// on lvalue references because of C++0x [dcl.typedef]p9,
1796 /// as follows:
1797 ///
1798 /// typedef int &ref; // lvalue, spelled lvalue
1799 /// typedef int &&rvref; // rvalue
1800 /// ref &a; // lvalue, inner ref, spelled lvalue
1801 /// ref &&a; // lvalue, inner ref
1802 /// rvref &a; // lvalue, inner ref, spelled lvalue
1803 /// rvref &&a; // rvalue, inner ref
1804 LLVM_PREFERRED_TYPE(bool)
1805 unsigned SpelledAsLValue : 1;
1806
1807 /// True if the inner type is a reference type. This only happens
1808 /// in non-canonical forms.
1809 LLVM_PREFERRED_TYPE(bool)
1810 unsigned InnerRef : 1;
1811 };
1812
1813 class TypeWithKeywordBitfields {
1814 friend class TypeWithKeyword;
1815
1816 LLVM_PREFERRED_TYPE(TypeBitfields)
1817 unsigned : NumTypeBits;
1818
1819 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1820 LLVM_PREFERRED_TYPE(ElaboratedTypeKeyword)
1821 unsigned Keyword : 8;
1822 };
1823
1824 enum { NumTypeWithKeywordBits = NumTypeBits + 8 };
1825
1826 class ElaboratedTypeBitfields {
1827 friend class ElaboratedType;
1828
1829 LLVM_PREFERRED_TYPE(TypeWithKeywordBitfields)
1830 unsigned : NumTypeWithKeywordBits;
1831
1832 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1833 LLVM_PREFERRED_TYPE(bool)
1834 unsigned HasOwnedTagDecl : 1;
1835 };
1836
1837 class VectorTypeBitfields {
1838 friend class VectorType;
1839 friend class DependentVectorType;
1840
1841 LLVM_PREFERRED_TYPE(TypeBitfields)
1842 unsigned : NumTypeBits;
1843
1844 /// The kind of vector, either a generic vector type or some
1845 /// target-specific vector type such as for AltiVec or Neon.
1846 LLVM_PREFERRED_TYPE(VectorKind)
1847 unsigned VecKind : 4;
1848 /// The number of elements in the vector.
1849 uint32_t NumElements;
1850 };
1851
1852 class AttributedTypeBitfields {
1853 friend class AttributedType;
1854
1855 LLVM_PREFERRED_TYPE(TypeBitfields)
1856 unsigned : NumTypeBits;
1857
1858 LLVM_PREFERRED_TYPE(attr::Kind)
1859 unsigned AttrKind : 32 - NumTypeBits;
1860 };
1861
1862 class AutoTypeBitfields {
1863 friend class AutoType;
1864
1865 LLVM_PREFERRED_TYPE(TypeBitfields)
1866 unsigned : NumTypeBits;
1867
1868 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1869 /// or '__auto_type'? AutoTypeKeyword value.
1870 LLVM_PREFERRED_TYPE(AutoTypeKeyword)
1871 unsigned Keyword : 2;
1872
1873 /// The number of template arguments in the type-constraints, which is
1874 /// expected to be able to hold at least 1024 according to [implimits].
1875 /// However as this limit is somewhat easy to hit with template
1876 /// metaprogramming we'd prefer to keep it as large as possible.
1877 /// At the moment it has been left as a non-bitfield since this type
1878 /// safely fits in 64 bits as an unsigned, so there is no reason to
1879 /// introduce the performance impact of a bitfield.
1880 unsigned NumArgs;
1881 };
1882
1883 class TypeOfBitfields {
1884 friend class TypeOfType;
1885 friend class TypeOfExprType;
1886
1887 LLVM_PREFERRED_TYPE(TypeBitfields)
1888 unsigned : NumTypeBits;
1889 LLVM_PREFERRED_TYPE(bool)
1890 unsigned IsUnqual : 1; // If true: typeof_unqual, else: typeof
1891 };
1892
1893 class UsingBitfields {
1894 friend class UsingType;
1895
1896 LLVM_PREFERRED_TYPE(TypeBitfields)
1897 unsigned : NumTypeBits;
1898
1899 /// True if the underlying type is different from the declared one.
1900 LLVM_PREFERRED_TYPE(bool)
1901 unsigned hasTypeDifferentFromDecl : 1;
1902 };
1903
1904 class TypedefBitfields {
1905 friend class TypedefType;
1906
1907 LLVM_PREFERRED_TYPE(TypeBitfields)
1908 unsigned : NumTypeBits;
1909
1910 /// True if the underlying type is different from the declared one.
1911 LLVM_PREFERRED_TYPE(bool)
1912 unsigned hasTypeDifferentFromDecl : 1;
1913 };
1914
1915 class SubstTemplateTypeParmTypeBitfields {
1916 friend class SubstTemplateTypeParmType;
1917
1918 LLVM_PREFERRED_TYPE(TypeBitfields)
1919 unsigned : NumTypeBits;
1920
1921 LLVM_PREFERRED_TYPE(bool)
1922 unsigned HasNonCanonicalUnderlyingType : 1;
1923
1924 // The index of the template parameter this substitution represents.
1925 unsigned Index : 15;
1926
1927 /// Represents the index within a pack if this represents a substitution
1928 /// from a pack expansion. This index starts at the end of the pack and
1929 /// increments towards the beginning.
1930 /// Positive non-zero number represents the index + 1.
1931 /// Zero means this is not substituted from an expansion.
1932 unsigned PackIndex : 16;
1933 };
1934
1935 class SubstTemplateTypeParmPackTypeBitfields {
1936 friend class SubstTemplateTypeParmPackType;
1937
1938 LLVM_PREFERRED_TYPE(TypeBitfields)
1939 unsigned : NumTypeBits;
1940
1941 // The index of the template parameter this substitution represents.
1942 unsigned Index : 16;
1943
1944 /// The number of template arguments in \c Arguments, which is
1945 /// expected to be able to hold at least 1024 according to [implimits].
1946 /// However as this limit is somewhat easy to hit with template
1947 /// metaprogramming we'd prefer to keep it as large as possible.
1948 unsigned NumArgs : 16;
1949 };
1950
1951 class TemplateSpecializationTypeBitfields {
1952 friend class TemplateSpecializationType;
1953
1954 LLVM_PREFERRED_TYPE(TypeBitfields)
1955 unsigned : NumTypeBits;
1956
1957 /// Whether this template specialization type is a substituted type alias.
1958 LLVM_PREFERRED_TYPE(bool)
1959 unsigned TypeAlias : 1;
1960
1961 /// The number of template arguments named in this class template
1962 /// specialization, which is expected to be able to hold at least 1024
1963 /// according to [implimits]. However, as this limit is somewhat easy to
1964 /// hit with template metaprogramming we'd prefer to keep it as large
1965 /// as possible. At the moment it has been left as a non-bitfield since
1966 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1967 /// to introduce the performance impact of a bitfield.
1968 unsigned NumArgs;
1969 };
1970
1971 class DependentTemplateSpecializationTypeBitfields {
1972 friend class DependentTemplateSpecializationType;
1973
1974 LLVM_PREFERRED_TYPE(TypeWithKeywordBitfields)
1975 unsigned : NumTypeWithKeywordBits;
1976
1977 /// The number of template arguments named in this class template
1978 /// specialization, which is expected to be able to hold at least 1024
1979 /// according to [implimits]. However, as this limit is somewhat easy to
1980 /// hit with template metaprogramming we'd prefer to keep it as large
1981 /// as possible. At the moment it has been left as a non-bitfield since
1982 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1983 /// to introduce the performance impact of a bitfield.
1984 unsigned NumArgs;
1985 };
1986
1987 class PackExpansionTypeBitfields {
1988 friend class PackExpansionType;
1989
1990 LLVM_PREFERRED_TYPE(TypeBitfields)
1991 unsigned : NumTypeBits;
1992
1993 /// The number of expansions that this pack expansion will
1994 /// generate when substituted (+1), which is expected to be able to
1995 /// hold at least 1024 according to [implimits]. However, as this limit
1996 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1997 /// keep it as large as possible. At the moment it has been left as a
1998 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1999 /// there is no reason to introduce the performance impact of a bitfield.
2000 ///
2001 /// This field will only have a non-zero value when some of the parameter
2002 /// packs that occur within the pattern have been substituted but others
2003 /// have not.
2004 unsigned NumExpansions;
2005 };
2006
2007 class CountAttributedTypeBitfields {
2008 friend class CountAttributedType;
2009
2010 LLVM_PREFERRED_TYPE(TypeBitfields)
2011 unsigned : NumTypeBits;
2012
2013 static constexpr unsigned NumCoupledDeclsBits = 4;
2014 unsigned NumCoupledDecls : NumCoupledDeclsBits;
2015 LLVM_PREFERRED_TYPE(bool)
2016 unsigned CountInBytes : 1;
2017 LLVM_PREFERRED_TYPE(bool)
2018 unsigned OrNull : 1;
2019 };
2020 static_assert(sizeof(CountAttributedTypeBitfields) <= sizeof(unsigned));
2021
2022 union {
2023 TypeBitfields TypeBits;
2024 ArrayTypeBitfields ArrayTypeBits;
2025 ConstantArrayTypeBitfields ConstantArrayTypeBits;
2026 AttributedTypeBitfields AttributedTypeBits;
2027 AutoTypeBitfields AutoTypeBits;
2028 TypeOfBitfields TypeOfBits;
2029 TypedefBitfields TypedefBits;
2030 UsingBitfields UsingBits;
2031 BuiltinTypeBitfields BuiltinTypeBits;
2032 FunctionTypeBitfields FunctionTypeBits;
2033 ObjCObjectTypeBitfields ObjCObjectTypeBits;
2034 ReferenceTypeBitfields ReferenceTypeBits;
2035 TypeWithKeywordBitfields TypeWithKeywordBits;
2036 ElaboratedTypeBitfields ElaboratedTypeBits;
2037 VectorTypeBitfields VectorTypeBits;
2038 SubstTemplateTypeParmTypeBitfields SubstTemplateTypeParmTypeBits;
2039 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
2040 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
2041 DependentTemplateSpecializationTypeBitfields
2042 DependentTemplateSpecializationTypeBits;
2043 PackExpansionTypeBitfields PackExpansionTypeBits;
2044 CountAttributedTypeBitfields CountAttributedTypeBits;
2045 };
2046
2047private:
2048 template <class T> friend class TypePropertyCache;
2049
2050 /// Set whether this type comes from an AST file.
2051 void setFromAST(bool V = true) const {
2052 TypeBits.FromAST = V;
2053 }
2054
2055protected:
2056 friend class ASTContext;
2057
2058 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
2059 : ExtQualsTypeCommonBase(this,
2060 canon.isNull() ? QualType(this_(), 0) : canon) {
2061 static_assert(sizeof(*this) <=
2062 alignof(decltype(*this)) + sizeof(ExtQualsTypeCommonBase),
2063 "changing bitfields changed sizeof(Type)!");
2064 static_assert(alignof(decltype(*this)) % TypeAlignment == 0,
2065 "Insufficient alignment!");
2066 TypeBits.TC = tc;
2067 TypeBits.Dependence = static_cast<unsigned>(Dependence);
2068 TypeBits.CacheValid = false;
2069 TypeBits.CachedLocalOrUnnamed = false;
2070 TypeBits.CachedLinkage = llvm::to_underlying(Linkage::Invalid);
2071 TypeBits.FromAST = false;
2072 }
2073
2074 // silence VC++ warning C4355: 'this' : used in base member initializer list
2075 Type *this_() { return this; }
2076
2077 void setDependence(TypeDependence D) {
2078 TypeBits.Dependence = static_cast<unsigned>(D);
2079 }
2080
2081 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
2082
2083public:
2084 friend class ASTReader;
2085 friend class ASTWriter;
2086 template <class T> friend class serialization::AbstractTypeReader;
2087 template <class T> friend class serialization::AbstractTypeWriter;
2088
2089 Type(const Type &) = delete;
2090 Type(Type &&) = delete;
2091 Type &operator=(const Type &) = delete;
2092 Type &operator=(Type &&) = delete;
2093
2094 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
2095
2096 /// Whether this type comes from an AST file.
2097 bool isFromAST() const { return TypeBits.FromAST; }
2098
2099 /// Whether this type is or contains an unexpanded parameter
2100 /// pack, used to support C++0x variadic templates.
2101 ///
2102 /// A type that contains a parameter pack shall be expanded by the
2103 /// ellipsis operator at some point. For example, the typedef in the
2104 /// following example contains an unexpanded parameter pack 'T':
2105 ///
2106 /// \code
2107 /// template<typename ...T>
2108 /// struct X {
2109 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
2110 /// };
2111 /// \endcode
2112 ///
2113 /// Note that this routine does not specify which
2114 bool containsUnexpandedParameterPack() const {
2115 return getDependence() & TypeDependence::UnexpandedPack;
2116 }
2117
2118 /// Determines if this type would be canonical if it had no further
2119 /// qualification.
2120 bool isCanonicalUnqualified() const {
2121 return CanonicalType == QualType(this, 0);
2122 }
2123
2124 /// Pull a single level of sugar off of this locally-unqualified type.
2125 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
2126 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
2127 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
2128
2129 /// As an extension, we classify types as one of "sized" or "sizeless";
2130 /// every type is one or the other. Standard types are all sized;
2131 /// sizeless types are purely an extension.
2132 ///
2133 /// Sizeless types contain data with no specified size, alignment,
2134 /// or layout.
2135 bool isSizelessType() const;
2136 bool isSizelessBuiltinType() const;
2137
2138 /// Returns true for all scalable vector types.
2139 bool isSizelessVectorType() const;
2140
2141 /// Returns true for SVE scalable vector types.
2142 bool isSVESizelessBuiltinType() const;
2143
2144 /// Returns true for RVV scalable vector types.
2145 bool isRVVSizelessBuiltinType() const;
2146
2147 /// Check if this is a WebAssembly Externref Type.
2148 bool isWebAssemblyExternrefType() const;
2149
2150 /// Returns true if this is a WebAssembly table type: either an array of
2151 /// reference types, or a pointer to a reference type (which can only be
2152 /// created by array to pointer decay).
2153 bool isWebAssemblyTableType() const;
2154
2155 /// Determines if this is a sizeless type supported by the
2156 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
2157 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
2158 bool isSveVLSBuiltinType() const;
2159
2160 /// Returns the representative type for the element of an SVE builtin type.
2161 /// This is used to represent fixed-length SVE vectors created with the
2162 /// 'arm_sve_vector_bits' type attribute as VectorType.
2163 QualType getSveEltType(const ASTContext &Ctx) const;
2164
2165 /// Determines if this is a sizeless type supported by the
2166 /// 'riscv_rvv_vector_bits' type attribute, which can be applied to a single
2167 /// RVV vector or mask.
2168 bool isRVVVLSBuiltinType() const;
2169
2170 /// Returns the representative type for the element of an RVV builtin type.
2171 /// This is used to represent fixed-length RVV vectors created with the
2172 /// 'riscv_rvv_vector_bits' type attribute as VectorType.
2173 QualType getRVVEltType(const ASTContext &Ctx) const;
2174
2175 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
2176 /// object types, function types, and incomplete types.
2177
2178 /// Return true if this is an incomplete type.
2179 /// A type that can describe objects, but which lacks information needed to
2180 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
2181 /// routine will need to determine if the size is actually required.
2182 ///
2183 /// Def If non-null, and the type refers to some kind of declaration
2184 /// that can be completed (such as a C struct, C++ class, or Objective-C
2185 /// class), will be set to the declaration.
2186 bool isIncompleteType(NamedDecl **Def = nullptr) const;
2187
2188 /// Return true if this is an incomplete or object
2189 /// type, in other words, not a function type.
2190 bool isIncompleteOrObjectType() const {
2191 return !isFunctionType();
2192 }
2193
2194 /// Determine whether this type is an object type.
2195 bool isObjectType() const {
2196 // C++ [basic.types]p8:
2197 // An object type is a (possibly cv-qualified) type that is not a
2198 // function type, not a reference type, and not a void type.
2199 return !isReferenceType() && !isFunctionType() && !isVoidType();
2200 }
2201
2202 /// Return true if this is a literal type
2203 /// (C++11 [basic.types]p10)
2204 bool isLiteralType(const ASTContext &Ctx) const;
2205
2206 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
2207 bool isStructuralType() const;
2208
2209 /// Test if this type is a standard-layout type.
2210 /// (C++0x [basic.type]p9)
2211 bool isStandardLayoutType() const;
2212
2213 /// Helper methods to distinguish type categories. All type predicates
2214 /// operate on the canonical type, ignoring typedefs and qualifiers.
2215
2216 /// Returns true if the type is a builtin type.
2217 bool isBuiltinType() const;
2218
2219 /// Test for a particular builtin type.
2220 bool isSpecificBuiltinType(unsigned K) const;
2221
2222 /// Test for a type which does not represent an actual type-system type but
2223 /// is instead used as a placeholder for various convenient purposes within
2224 /// Clang. All such types are BuiltinTypes.
2225 bool isPlaceholderType() const;
2226 const BuiltinType *getAsPlaceholderType() const;
2227
2228 /// Test for a specific placeholder type.
2229 bool isSpecificPlaceholderType(unsigned K) const;
2230
2231 /// Test for a placeholder type other than Overload; see
2232 /// BuiltinType::isNonOverloadPlaceholderType.
2233 bool isNonOverloadPlaceholderType() const;
2234
2235 /// isIntegerType() does *not* include complex integers (a GCC extension).
2236 /// isComplexIntegerType() can be used to test for complex integers.
2237 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
2238 bool isEnumeralType() const;
2239
2240 /// Determine whether this type is a scoped enumeration type.
2241 bool isScopedEnumeralType() const;
2242 bool isBooleanType() const;
2243 bool isCharType() const;
2244 bool isWideCharType() const;
2245 bool isChar8Type() const;
2246 bool isChar16Type() const;
2247 bool isChar32Type() const;
2248 bool isAnyCharacterType() const;
2249 bool isIntegralType(const ASTContext &Ctx) const;
2250
2251 /// Determine whether this type is an integral or enumeration type.
2252 bool isIntegralOrEnumerationType() const;
2253
2254 /// Determine whether this type is an integral or unscoped enumeration type.
2255 bool isIntegralOrUnscopedEnumerationType() const;
2256 bool isUnscopedEnumerationType() const;
2257
2258 /// Floating point categories.
2259 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2260 /// isComplexType() does *not* include complex integers (a GCC extension).
2261 /// isComplexIntegerType() can be used to test for complex integers.
2262 bool isComplexType() const; // C99 6.2.5p11 (complex)
2263 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2264 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2265 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2266 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2267 bool isFloat32Type() const;
2268 bool isDoubleType() const;
2269 bool isBFloat16Type() const;
2270 bool isFloat128Type() const;
2271 bool isIbm128Type() const;
2272 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2273 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2274 bool isVoidType() const; // C99 6.2.5p19
2275 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2276 bool isAggregateType() const;
2277 bool isFundamentalType() const;
2278 bool isCompoundType() const;
2279
2280 // Type Predicates: Check to see if this type is structurally the specified
2281 // type, ignoring typedefs and qualifiers.
2282 bool isFunctionType() const;
2283 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2284 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2285 bool isPointerType() const;
2286 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2287 bool isCountAttributedType() const;
2288 bool isBlockPointerType() const;
2289 bool isVoidPointerType() const;
2290 bool isReferenceType() const;
2291 bool isLValueReferenceType() const;
2292 bool isRValueReferenceType() const;
2293 bool isObjectPointerType() const;
2294 bool isFunctionPointerType() const;
2295 bool isFunctionReferenceType() const;
2296 bool isMemberPointerType() const;
2297 bool isMemberFunctionPointerType() const;
2298 bool isMemberDataPointerType() const;
2299 bool isArrayType() const;
2300 bool isConstantArrayType() const;
2301 bool isIncompleteArrayType() const;
2302 bool isVariableArrayType() const;
2303 bool isArrayParameterType() const;
2304 bool isDependentSizedArrayType() const;
2305 bool isRecordType() const;
2306 bool isClassType() const;
2307 bool isStructureType() const;
2308 bool isObjCBoxableRecordType() const;
2309 bool isInterfaceType() const;
2310 bool isStructureOrClassType() const;
2311 bool isUnionType() const;
2312 bool isComplexIntegerType() const; // GCC _Complex integer type.
2313 bool isVectorType() const; // GCC vector type.
2314 bool isExtVectorType() const; // Extended vector type.
2315 bool isExtVectorBoolType() const; // Extended vector type with bool element.
2316 bool isMatrixType() const; // Matrix type.
2317 bool isConstantMatrixType() const; // Constant matrix type.
2318 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2319 bool isObjCObjectPointerType() const; // pointer to ObjC object
2320 bool isObjCRetainableType() const; // ObjC object or block pointer
2321 bool isObjCLifetimeType() const; // (array of)* retainable type
2322 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2323 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2324 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2325 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2326 // for the common case.
2327 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2328 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2329 bool isObjCQualifiedIdType() const; // id<foo>
2330 bool isObjCQualifiedClassType() const; // Class<foo>
2331 bool isObjCObjectOrInterfaceType() const;
2332 bool isObjCIdType() const; // id
2333 bool isDecltypeType() const;
2334 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2335 /// qualifier?
2336 ///
2337 /// This approximates the answer to the following question: if this
2338 /// translation unit were compiled in ARC, would this type be qualified
2339 /// with __unsafe_unretained?
2340 bool isObjCInertUnsafeUnretainedType() const {
2341 return hasAttr(attr::ObjCInertUnsafeUnretained);
2342 }
2343
2344 /// Whether the type is Objective-C 'id' or a __kindof type of an
2345 /// object type, e.g., __kindof NSView * or __kindof id
2346 /// <NSCopying>.
2347 ///
2348 /// \param bound Will be set to the bound on non-id subtype types,
2349 /// which will be (possibly specialized) Objective-C class type, or
2350 /// null for 'id.
2351 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2352 const ObjCObjectType *&bound) const;
2353
2354 bool isObjCClassType() const; // Class
2355
2356 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2357 /// Class type, e.g., __kindof Class <NSCopying>.
2358 ///
2359 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2360 /// here because Objective-C's type system cannot express "a class
2361 /// object for a subclass of NSFoo".
2362 bool isObjCClassOrClassKindOfType() const;
2363
2364 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2365 bool isObjCSelType() const; // Class
2366 bool isObjCBuiltinType() const; // 'id' or 'Class'
2367 bool isObjCARCBridgableType() const;
2368 bool isCARCBridgableType() const;
2369 bool isTemplateTypeParmType() const; // C++ template type parameter
2370 bool isNullPtrType() const; // C++11 std::nullptr_t or
2371 // C23 nullptr_t
2372 bool isNothrowT() const; // C++ std::nothrow_t
2373 bool isAlignValT() const; // C++17 std::align_val_t
2374 bool isStdByteType() const; // C++17 std::byte
2375 bool isAtomicType() const; // C11 _Atomic()
2376 bool isUndeducedAutoType() const; // C++11 auto or
2377 // C++14 decltype(auto)
2378 bool isTypedefNameType() const; // typedef or alias template
2379
2380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2381 bool is##Id##Type() const;
2382#include "clang/Basic/OpenCLImageTypes.def"
2383
2384 bool isImageType() const; // Any OpenCL image type
2385
2386 bool isSamplerT() const; // OpenCL sampler_t
2387 bool isEventT() const; // OpenCL event_t
2388 bool isClkEventT() const; // OpenCL clk_event_t
2389 bool isQueueT() const; // OpenCL queue_t
2390 bool isReserveIDT() const; // OpenCL reserve_id_t
2391
2392#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2393 bool is##Id##Type() const;
2394#include "clang/Basic/OpenCLExtensionTypes.def"
2395 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2396 bool isOCLIntelSubgroupAVCType() const;
2397 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2398
2399 bool isPipeType() const; // OpenCL pipe type
2400 bool isBitIntType() const; // Bit-precise integer type
2401 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2402
2403 /// Determines if this type, which must satisfy
2404 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2405 /// than implicitly __strong.
2406 bool isObjCARCImplicitlyUnretainedType() const;
2407
2408 /// Check if the type is the CUDA device builtin surface type.
2409 bool isCUDADeviceBuiltinSurfaceType() const;
2410 /// Check if the type is the CUDA device builtin texture type.
2411 bool isCUDADeviceBuiltinTextureType() const;
2412
2413 /// Return the implicit lifetime for this type, which must not be dependent.
2414 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2415
2416 enum ScalarTypeKind {
2417 STK_CPointer,
2418 STK_BlockPointer,
2419 STK_ObjCObjectPointer,
2420 STK_MemberPointer,
2421 STK_Bool,
2422 STK_Integral,
2423 STK_Floating,
2424 STK_IntegralComplex,
2425 STK_FloatingComplex,
2426 STK_FixedPoint
2427 };
2428
2429 /// Given that this is a scalar type, classify it.
2430 ScalarTypeKind getScalarTypeKind() const;
2431
2432 TypeDependence getDependence() const {
2433 return static_cast<TypeDependence>(TypeBits.Dependence);
2434 }
2435
2436 /// Whether this type is an error type.
2437 bool containsErrors() const {
2438 return getDependence() & TypeDependence::Error;
2439 }
2440
2441 /// Whether this type is a dependent type, meaning that its definition
2442 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2443 bool isDependentType() const {
2444 return getDependence() & TypeDependence::Dependent;
2445 }
2446
2447 /// Determine whether this type is an instantiation-dependent type,
2448 /// meaning that the type involves a template parameter (even if the
2449 /// definition does not actually depend on the type substituted for that
2450 /// template parameter).
2451 bool isInstantiationDependentType() const {
2452 return getDependence() & TypeDependence::Instantiation;
2453 }
2454
2455 /// Determine whether this type is an undeduced type, meaning that
2456 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2457 /// deduced.
2458 bool isUndeducedType() const;
2459
2460 /// Whether this type is a variably-modified type (C99 6.7.5).
2461 bool isVariablyModifiedType() const {
2462 return getDependence() & TypeDependence::VariablyModified;
2463 }
2464
2465 /// Whether this type involves a variable-length array type
2466 /// with a definite size.
2467 bool hasSizedVLAType() const;
2468
2469 /// Whether this type is or contains a local or unnamed type.
2470 bool hasUnnamedOrLocalType() const;
2471
2472 bool isOverloadableType() const;
2473
2474 /// Determine wither this type is a C++ elaborated-type-specifier.
2475 bool isElaboratedTypeSpecifier() const;
2476
2477 bool canDecayToPointerType() const;
2478
2479 /// Whether this type is represented natively as a pointer. This includes
2480 /// pointers, references, block pointers, and Objective-C interface,
2481 /// qualified id, and qualified interface types, as well as nullptr_t.
2482 bool hasPointerRepresentation() const;
2483
2484 /// Whether this type can represent an objective pointer type for the
2485 /// purpose of GC'ability
2486 bool hasObjCPointerRepresentation() const;
2487
2488 /// Determine whether this type has an integer representation
2489 /// of some sort, e.g., it is an integer type or a vector.
2490 bool hasIntegerRepresentation() const;
2491
2492 /// Determine whether this type has an signed integer representation
2493 /// of some sort, e.g., it is an signed integer type or a vector.
2494 bool hasSignedIntegerRepresentation() const;
2495
2496 /// Determine whether this type has an unsigned integer representation
2497 /// of some sort, e.g., it is an unsigned integer type or a vector.
2498 bool hasUnsignedIntegerRepresentation() const;
2499
2500 /// Determine whether this type has a floating-point representation
2501 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2502 bool hasFloatingRepresentation() const;
2503
2504 // Type Checking Functions: Check to see if this type is structurally the
2505 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2506 // the best type we can.
2507 const RecordType *getAsStructureType() const;
2508 /// NOTE: getAs*ArrayType are methods on ASTContext.
2509 const RecordType *getAsUnionType() const;
2510 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2511 const ObjCObjectType *getAsObjCInterfaceType() const;
2512
2513 // The following is a convenience method that returns an ObjCObjectPointerType
2514 // for object declared using an interface.
2515 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2516 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2517 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2518 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2519
2520 /// Retrieves the CXXRecordDecl that this type refers to, either
2521 /// because the type is a RecordType or because it is the injected-class-name
2522 /// type of a class template or class template partial specialization.
2523 CXXRecordDecl *getAsCXXRecordDecl() const;
2524
2525 /// Retrieves the RecordDecl this type refers to.
2526 RecordDecl *getAsRecordDecl() const;
2527
2528 /// Retrieves the TagDecl that this type refers to, either
2529 /// because the type is a TagType or because it is the injected-class-name
2530 /// type of a class template or class template partial specialization.
2531 TagDecl *getAsTagDecl() const;
2532
2533 /// If this is a pointer or reference to a RecordType, return the
2534 /// CXXRecordDecl that the type refers to.
2535 ///
2536 /// If this is not a pointer or reference, or the type being pointed to does
2537 /// not refer to a CXXRecordDecl, returns NULL.
2538 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2539
2540 /// Get the DeducedType whose type will be deduced for a variable with
2541 /// an initializer of this type. This looks through declarators like pointer
2542 /// types, but not through decltype or typedefs.
2543 DeducedType *getContainedDeducedType() const;
2544
2545 /// Get the AutoType whose type will be deduced for a variable with
2546 /// an initializer of this type. This looks through declarators like pointer
2547 /// types, but not through decltype or typedefs.
2548 AutoType *getContainedAutoType() const {
2549 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2550 }
2551
2552 /// Determine whether this type was written with a leading 'auto'
2553 /// corresponding to a trailing return type (possibly for a nested
2554 /// function type within a pointer to function type or similar).
2555 bool hasAutoForTrailingReturnType() const;
2556
2557 /// Member-template getAs<specific type>'. Look through sugar for
2558 /// an instance of \<specific type>. This scheme will eventually
2559 /// replace the specific getAsXXXX methods above.
2560 ///
2561 /// There are some specializations of this member template listed
2562 /// immediately following this class.
2563 template <typename T> const T *getAs() const;
2564
2565 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2566 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2567 /// This is used when you need to walk over sugar nodes that represent some
2568 /// kind of type adjustment from a type that was written as a \<specific type>
2569 /// to another type that is still canonically a \<specific type>.
2570 template <typename T> const T *getAsAdjusted() const;
2571
2572 /// A variant of getAs<> for array types which silently discards
2573 /// qualifiers from the outermost type.
2574 const ArrayType *getAsArrayTypeUnsafe() const;
2575
2576 /// Member-template castAs<specific type>. Look through sugar for
2577 /// the underlying instance of \<specific type>.
2578 ///
2579 /// This method has the same relationship to getAs<T> as cast<T> has
2580 /// to dyn_cast<T>; which is to say, the underlying type *must*
2581 /// have the intended type, and this method will never return null.
2582 template <typename T> const T *castAs() const;
2583
2584 /// A variant of castAs<> for array type which silently discards
2585 /// qualifiers from the outermost type.
2586 const ArrayType *castAsArrayTypeUnsafe() const;
2587
2588 /// Determine whether this type had the specified attribute applied to it
2589 /// (looking through top-level type sugar).
2590 bool hasAttr(attr::Kind AK) const;
2591
2592 /// Get the base element type of this type, potentially discarding type
2593 /// qualifiers. This should never be used when type qualifiers
2594 /// are meaningful.
2595 const Type *getBaseElementTypeUnsafe() const;
2596
2597 /// If this is an array type, return the element type of the array,
2598 /// potentially with type qualifiers missing.
2599 /// This should never be used when type qualifiers are meaningful.
2600 const Type *getArrayElementTypeNoTypeQual() const;
2601
2602 /// If this is a pointer type, return the pointee type.
2603 /// If this is an array type, return the array element type.
2604 /// This should never be used when type qualifiers are meaningful.
2605 const Type *getPointeeOrArrayElementType() const;
2606
2607 /// If this is a pointer, ObjC object pointer, or block
2608 /// pointer, this returns the respective pointee.
2609 QualType getPointeeType() const;
2610
2611 /// Return the specified type with any "sugar" removed from the type,
2612 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2613 const Type *getUnqualifiedDesugaredType() const;
2614
2615 /// Return true if this is an integer type that is
2616 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2617 /// or an enum decl which has a signed representation.
2618 bool isSignedIntegerType() const;
2619
2620 /// Return true if this is an integer type that is
2621 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2622 /// or an enum decl which has an unsigned representation.
2623 bool isUnsignedIntegerType() const;
2624
2625 /// Determines whether this is an integer type that is signed or an
2626 /// enumeration types whose underlying type is a signed integer type.
2627 bool isSignedIntegerOrEnumerationType() const;
2628
2629 /// Determines whether this is an integer type that is unsigned or an
2630 /// enumeration types whose underlying type is a unsigned integer type.
2631 bool isUnsignedIntegerOrEnumerationType() const;
2632
2633 /// Return true if this is a fixed point type according to
2634 /// ISO/IEC JTC1 SC22 WG14 N1169.
2635 bool isFixedPointType() const;
2636
2637 /// Return true if this is a fixed point or integer type.
2638 bool isFixedPointOrIntegerType() const;
2639
2640 /// Return true if this can be converted to (or from) a fixed point type.
2641 bool isConvertibleToFixedPointType() const;
2642
2643 /// Return true if this is a saturated fixed point type according to
2644 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2645 bool isSaturatedFixedPointType() const;
2646
2647 /// Return true if this is a saturated fixed point type according to
2648 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2649 bool isUnsaturatedFixedPointType() const;
2650
2651 /// Return true if this is a fixed point type that is signed according
2652 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2653 bool isSignedFixedPointType() const;
2654
2655 /// Return true if this is a fixed point type that is unsigned according
2656 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2657 bool isUnsignedFixedPointType() const;
2658
2659 /// Return true if this is not a variable sized type,
2660 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2661 /// incomplete types.
2662 bool isConstantSizeType() const;
2663
2664 /// Returns true if this type can be represented by some
2665 /// set of type specifiers.
2666 bool isSpecifierType() const;
2667
2668 /// Determine the linkage of this type.
2669 Linkage getLinkage() const;
2670
2671 /// Determine the visibility of this type.
2672 Visibility getVisibility() const {
2673 return getLinkageAndVisibility().getVisibility();
2674 }
2675
2676 /// Return true if the visibility was explicitly set is the code.
2677 bool isVisibilityExplicit() const {
2678 return getLinkageAndVisibility().isVisibilityExplicit();
2679 }
2680
2681 /// Determine the linkage and visibility of this type.
2682 LinkageInfo getLinkageAndVisibility() const;
2683
2684 /// True if the computed linkage is valid. Used for consistency
2685 /// checking. Should always return true.
2686 bool isLinkageValid() const;
2687
2688 /// Determine the nullability of the given type.
2689 ///
2690 /// Note that nullability is only captured as sugar within the type
2691 /// system, not as part of the canonical type, so nullability will
2692 /// be lost by canonicalization and desugaring.
2693 std::optional<NullabilityKind> getNullability() const;
2694
2695 /// Determine whether the given type can have a nullability
2696 /// specifier applied to it, i.e., if it is any kind of pointer type.
2697 ///
2698 /// \param ResultIfUnknown The value to return if we don't yet know whether
2699 /// this type can have nullability because it is dependent.
2700 bool canHaveNullability(bool ResultIfUnknown = true) const;
2701
2702 /// Retrieve the set of substitutions required when accessing a member
2703 /// of the Objective-C receiver type that is declared in the given context.
2704 ///
2705 /// \c *this is the type of the object we're operating on, e.g., the
2706 /// receiver for a message send or the base of a property access, and is
2707 /// expected to be of some object or object pointer type.
2708 ///
2709 /// \param dc The declaration context for which we are building up a
2710 /// substitution mapping, which should be an Objective-C class, extension,
2711 /// category, or method within.
2712 ///
2713 /// \returns an array of type arguments that can be substituted for
2714 /// the type parameters of the given declaration context in any type described
2715 /// within that context, or an empty optional to indicate that no
2716 /// substitution is required.
2717 std::optional<ArrayRef<QualType>>
2718 getObjCSubstitutions(const DeclContext *dc) const;
2719
2720 /// Determines if this is an ObjC interface type that may accept type
2721 /// parameters.
2722 bool acceptsObjCTypeParams() const;
2723
2724 const char *getTypeClassName() const;
2725
2726 QualType getCanonicalTypeInternal() const {
2727 return CanonicalType;
2728 }
2729
2730 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2731 void dump() const;
2732 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2733};
2734
2735/// This will check for a TypedefType by removing any existing sugar
2736/// until it reaches a TypedefType or a non-sugared type.
2737template <> const TypedefType *Type::getAs() const;
2738template <> const UsingType *Type::getAs() const;
2739
2740/// This will check for a TemplateSpecializationType by removing any
2741/// existing sugar until it reaches a TemplateSpecializationType or a
2742/// non-sugared type.
2743template <> const TemplateSpecializationType *Type::getAs() const;
2744
2745/// This will check for an AttributedType by removing any existing sugar
2746/// until it reaches an AttributedType or a non-sugared type.
2747template <> const AttributedType *Type::getAs() const;
2748
2749/// This will check for a BoundsAttributedType by removing any existing
2750/// sugar until it reaches an BoundsAttributedType or a non-sugared type.
2751template <> const BoundsAttributedType *Type::getAs() const;
2752
2753/// This will check for a CountAttributedType by removing any existing
2754/// sugar until it reaches an CountAttributedType or a non-sugared type.
2755template <> const CountAttributedType *Type::getAs() const;
2756
2757// We can do canonical leaf types faster, because we don't have to
2758// worry about preserving child type decoration.
2759#define TYPE(Class, Base)
2760#define LEAF_TYPE(Class) \
2761template <> inline const Class##Type *Type::getAs() const { \
2762 return dyn_cast<Class##Type>(CanonicalType); \
2763} \
2764template <> inline const Class##Type *Type::castAs() const { \
2765 return cast<Class##Type>(CanonicalType); \
2766}
2767#include "clang/AST/TypeNodes.inc"
2768
2769/// This class is used for builtin types like 'int'. Builtin
2770/// types are always canonical and have a literal name field.
2771class BuiltinType : public Type {
2772public:
2773 enum Kind {
2774// OpenCL image types
2775#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2776#include "clang/Basic/OpenCLImageTypes.def"
2777// OpenCL extension types
2778#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2779#include "clang/Basic/OpenCLExtensionTypes.def"
2780// SVE Types
2781#define SVE_TYPE(Name, Id, SingletonId) Id,
2782#include "clang/Basic/AArch64SVEACLETypes.def"
2783// PPC MMA Types
2784#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2785#include "clang/Basic/PPCTypes.def"
2786// RVV Types
2787#define RVV_TYPE(Name, Id, SingletonId) Id,
2788#include "clang/Basic/RISCVVTypes.def"
2789// WebAssembly reference types
2790#define WASM_TYPE(Name, Id, SingletonId) Id,
2791#include "clang/Basic/WebAssemblyReferenceTypes.def"
2792// All other builtin types
2793#define BUILTIN_TYPE(Id, SingletonId) Id,
2794#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2795#include "clang/AST/BuiltinTypes.def"
2796 };
2797
2798private:
2799 friend class ASTContext; // ASTContext creates these.
2800
2801 BuiltinType(Kind K)
2802 : Type(Builtin, QualType(),
2803 K == Dependent ? TypeDependence::DependentInstantiation
2804 : TypeDependence::None) {
2805 static_assert(Kind::LastKind <
2806 (1 << BuiltinTypeBitfields::NumOfBuiltinTypeBits) &&
2807 "Defined builtin type exceeds the allocated space for serial "
2808 "numbering");
2809 BuiltinTypeBits.Kind = K;
2810 }
2811
2812public:
2813 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2814 StringRef getName(const PrintingPolicy &Policy) const;
2815
2816 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2817 // The StringRef is null-terminated.
2818 StringRef str = getName(Policy);
2819 assert(!str.empty() && str.data()[str.size()] == '\0');
2820 return str.data();
2821 }
2822
2823 bool isSugared() const { return false; }
2824 QualType desugar() const { return QualType(this, 0); }
2825
2826 bool isInteger() const {
2827 return getKind() >= Bool && getKind() <= Int128;
2828 }
2829
2830 bool isSignedInteger() const {
2831 return getKind() >= Char_S && getKind() <= Int128;
2832 }
2833
2834 bool isUnsignedInteger() const {
2835 return getKind() >= Bool && getKind() <= UInt128;
2836 }
2837
2838 bool isFloatingPoint() const {
2839 return getKind() >= Half && getKind() <= Ibm128;
2840 }
2841
2842 bool isSVEBool() const { return getKind() == Kind::SveBool; }
2843
2844 bool isSVECount() const { return getKind() == Kind::SveCount; }
2845
2846 /// Determines whether the given kind corresponds to a placeholder type.
2847 static bool isPlaceholderTypeKind(Kind K) {
2848 return K >= Overload;
2849 }
2850
2851 /// Determines whether this type is a placeholder type, i.e. a type
2852 /// which cannot appear in arbitrary positions in a fully-formed
2853 /// expression.
2854 bool isPlaceholderType() const {
2855 return isPlaceholderTypeKind(K: getKind());
2856 }
2857
2858 /// Determines whether this type is a placeholder type other than
2859 /// Overload. Most placeholder types require only syntactic
2860 /// information about their context in order to be resolved (e.g.
2861 /// whether it is a call expression), which means they can (and
2862 /// should) be resolved in an earlier "phase" of analysis.
2863 /// Overload expressions sometimes pick up further information
2864 /// from their context, like whether the context expects a
2865 /// specific function-pointer type, and so frequently need
2866 /// special treatment.
2867 bool isNonOverloadPlaceholderType() const {
2868 return getKind() > Overload;
2869 }
2870
2871 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2872};
2873
2874/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2875/// types (_Complex float etc) as well as the GCC integer complex extensions.
2876class ComplexType : public Type, public llvm::FoldingSetNode {
2877 friend class ASTContext; // ASTContext creates these.
2878
2879 QualType ElementType;
2880
2881 ComplexType(QualType Element, QualType CanonicalPtr)
2882 : Type(Complex, CanonicalPtr, Element->getDependence()),
2883 ElementType(Element) {}
2884
2885public:
2886 QualType getElementType() const { return ElementType; }
2887
2888 bool isSugared() const { return false; }
2889 QualType desugar() const { return QualType(this, 0); }
2890
2891 void Profile(llvm::FoldingSetNodeID &ID) {
2892 Profile(ID, Element: getElementType());
2893 }
2894
2895 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2896 ID.AddPointer(Ptr: Element.getAsOpaquePtr());
2897 }
2898
2899 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2900};
2901
2902/// Sugar for parentheses used when specifying types.
2903class ParenType : public Type, public llvm::FoldingSetNode {
2904 friend class ASTContext; // ASTContext creates these.
2905
2906 QualType Inner;
2907
2908 ParenType(QualType InnerType, QualType CanonType)
2909 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2910
2911public:
2912 QualType getInnerType() const { return Inner; }
2913
2914 bool isSugared() const { return true; }
2915 QualType desugar() const { return getInnerType(); }
2916
2917 void Profile(llvm::FoldingSetNodeID &ID) {
2918 Profile(ID, Inner: getInnerType());
2919 }
2920
2921 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2922 Inner.Profile(ID);
2923 }
2924
2925 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2926};
2927
2928/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2929class PointerType : public Type, public llvm::FoldingSetNode {
2930 friend class ASTContext; // ASTContext creates these.
2931
2932 QualType PointeeType;
2933
2934 PointerType(QualType Pointee, QualType CanonicalPtr)
2935 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2936 PointeeType(Pointee) {}
2937
2938public:
2939 QualType getPointeeType() const { return PointeeType; }
2940
2941 bool isSugared() const { return false; }
2942 QualType desugar() const { return QualType(this, 0); }
2943
2944 void Profile(llvm::FoldingSetNodeID &ID) {
2945 Profile(ID, Pointee: getPointeeType());
2946 }
2947
2948 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2949 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
2950 }
2951
2952 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2953};
2954
2955/// [BoundsSafety] Represents information of declarations referenced by the
2956/// arguments of the `counted_by` attribute and the likes.
2957class TypeCoupledDeclRefInfo {
2958public:
2959 using BaseTy = llvm::PointerIntPair<ValueDecl *, 1, unsigned>;
2960
2961private:
2962 enum {
2963 DerefShift = 0,
2964 DerefMask = 1,
2965 };
2966 BaseTy Data;
2967
2968public:
2969 /// \p D is to a declaration referenced by the argument of attribute. \p Deref
2970 /// indicates whether \p D is referenced as a dereferenced form, e.g., \p
2971 /// Deref is true for `*n` in `int *__counted_by(*n)`.
2972 TypeCoupledDeclRefInfo(ValueDecl *D = nullptr, bool Deref = false);
2973
2974 bool isDeref() const;
2975 ValueDecl *getDecl() const;
2976 unsigned getInt() const;
2977 void *getOpaqueValue() const;
2978 bool operator==(const TypeCoupledDeclRefInfo &Other) const;
2979 void setFromOpaqueValue(void *V);
2980};
2981
2982/// [BoundsSafety] Represents a parent type class for CountAttributedType and
2983/// similar sugar types that will be introduced to represent a type with a
2984/// bounds attribute.
2985///
2986/// Provides a common interface to navigate declarations referred to by the
2987/// bounds expression.
2988
2989class BoundsAttributedType : public Type, public llvm::FoldingSetNode {
2990 QualType WrappedTy;
2991
2992protected:
2993 ArrayRef<TypeCoupledDeclRefInfo> Decls; // stored in trailing objects
2994
2995 BoundsAttributedType(TypeClass TC, QualType Wrapped, QualType Canon);
2996
2997public:
2998 bool isSugared() const { return true; }
2999 QualType desugar() const { return WrappedTy; }
3000
3001 using decl_iterator = const TypeCoupledDeclRefInfo *;
3002 using decl_range = llvm::iterator_range<decl_iterator>;
3003
3004 decl_iterator dependent_decl_begin() const { return Decls.begin(); }
3005 decl_iterator dependent_decl_end() const { return Decls.end(); }
3006
3007 unsigned getNumCoupledDecls() const { return Decls.size(); }
3008
3009 decl_range dependent_decls() const {
3010 return decl_range(dependent_decl_begin(), dependent_decl_end());
3011 }
3012
3013 ArrayRef<TypeCoupledDeclRefInfo> getCoupledDecls() const {
3014 return {dependent_decl_begin(), dependent_decl_end()};
3015 }
3016
3017 bool referencesFieldDecls() const;
3018
3019 static bool classof(const Type *T) {
3020 // Currently, only `class CountAttributedType` inherits
3021 // `BoundsAttributedType` but the subclass will grow as we add more bounds
3022 // annotations.
3023 switch (T->getTypeClass()) {
3024 case CountAttributed:
3025 return true;
3026 default:
3027 return false;
3028 }
3029 }
3030};
3031
3032/// Represents a sugar type with `__counted_by` or `__sized_by` annotations,
3033/// including their `_or_null` variants.
3034class CountAttributedType final
3035 : public BoundsAttributedType,
3036 public llvm::TrailingObjects<CountAttributedType,
3037 TypeCoupledDeclRefInfo> {
3038 friend class ASTContext;
3039
3040 Expr *CountExpr;
3041 /// \p CountExpr represents the argument of __counted_by or the likes. \p
3042 /// CountInBytes indicates that \p CountExpr is a byte count (i.e.,
3043 /// __sized_by(_or_null)) \p OrNull means it's an or_null variant (i.e.,
3044 /// __counted_by_or_null or __sized_by_or_null) \p CoupledDecls contains the
3045 /// list of declarations referenced by \p CountExpr, which the type depends on
3046 /// for the bounds information.
3047 CountAttributedType(QualType Wrapped, QualType Canon, Expr *CountExpr,
3048 bool CountInBytes, bool OrNull,
3049 ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls);
3050
3051 unsigned numTrailingObjects(OverloadToken<TypeCoupledDeclRefInfo>) const {
3052 return CountAttributedTypeBits.NumCoupledDecls;
3053 }
3054
3055public:
3056 enum DynamicCountPointerKind {
3057 CountedBy = 0,
3058 SizedBy,
3059 CountedByOrNull,
3060 SizedByOrNull,
3061 };
3062
3063 Expr *getCountExpr() const { return CountExpr; }
3064 bool isCountInBytes() const { return CountAttributedTypeBits.CountInBytes; }
3065 bool isOrNull() const { return CountAttributedTypeBits.OrNull; }
3066
3067 DynamicCountPointerKind getKind() const {
3068 if (isOrNull())
3069 return isCountInBytes() ? SizedByOrNull : CountedByOrNull;
3070 return isCountInBytes() ? SizedBy : CountedBy;
3071 }
3072
3073 void Profile(llvm::FoldingSetNodeID &ID) {
3074 Profile(ID, desugar(), CountExpr, isCountInBytes(), isOrNull());
3075 }
3076
3077 static void Profile(llvm::FoldingSetNodeID &ID, QualType WrappedTy,
3078 Expr *CountExpr, bool CountInBytes, bool Nullable);
3079
3080 static bool classof(const Type *T) {
3081 return T->getTypeClass() == CountAttributed;
3082 }
3083};
3084
3085/// Represents a type which was implicitly adjusted by the semantic
3086/// engine for arbitrary reasons. For example, array and function types can
3087/// decay, and function types can have their calling conventions adjusted.
3088class AdjustedType : public Type, public llvm::FoldingSetNode {
3089 QualType OriginalTy;
3090 QualType AdjustedTy;
3091
3092protected:
3093 friend class ASTContext; // ASTContext creates these.
3094
3095 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
3096 QualType CanonicalPtr)
3097 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
3098 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
3099
3100public:
3101 QualType getOriginalType() const { return OriginalTy; }
3102 QualType getAdjustedType() const { return AdjustedTy; }
3103
3104 bool isSugared() const { return true; }
3105 QualType desugar() const { return AdjustedTy; }
3106
3107 void Profile(llvm::FoldingSetNodeID &ID) {
3108 Profile(ID, OriginalTy, AdjustedTy);
3109 }
3110
3111 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
3112 ID.AddPointer(Ptr: Orig.getAsOpaquePtr());
3113 ID.AddPointer(Ptr: New.getAsOpaquePtr());
3114 }
3115
3116 static bool classof(const Type *T) {
3117 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
3118 }
3119};
3120
3121/// Represents a pointer type decayed from an array or function type.
3122class DecayedType : public AdjustedType {
3123 friend class ASTContext; // ASTContext creates these.
3124
3125 inline
3126 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
3127
3128public:
3129 QualType getDecayedType() const { return getAdjustedType(); }
3130
3131 inline QualType getPointeeType() const;
3132
3133 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
3134};
3135
3136/// Pointer to a block type.
3137/// This type is to represent types syntactically represented as
3138/// "void (^)(int)", etc. Pointee is required to always be a function type.
3139class BlockPointerType : public Type, public llvm::FoldingSetNode {
3140 friend class ASTContext; // ASTContext creates these.
3141
3142 // Block is some kind of pointer type
3143 QualType PointeeType;
3144
3145 BlockPointerType(QualType Pointee, QualType CanonicalCls)
3146 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
3147 PointeeType(Pointee) {}
3148
3149public:
3150 // Get the pointee type. Pointee is required to always be a function type.
3151 QualType getPointeeType() const { return PointeeType; }
3152
3153 bool isSugared() const { return false; }
3154 QualType desugar() const { return QualType(this, 0); }
3155
3156 void Profile(llvm::FoldingSetNodeID &ID) {
3157 Profile(ID, Pointee: getPointeeType());
3158 }
3159
3160 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
3161 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
3162 }
3163
3164 static bool classof(const Type *T) {
3165 return T->getTypeClass() == BlockPointer;
3166 }
3167};
3168
3169/// Base for LValueReferenceType and RValueReferenceType
3170class ReferenceType : public Type, public llvm::FoldingSetNode {
3171 QualType PointeeType;
3172
3173protected:
3174 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
3175 bool SpelledAsLValue)
3176 : Type(tc, CanonicalRef, Referencee->getDependence()),
3177 PointeeType(Referencee) {
3178 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
3179 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
3180 }
3181
3182public:
3183 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
3184 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
3185
3186 QualType getPointeeTypeAsWritten() const { return PointeeType; }
3187
3188 QualType getPointeeType() const {
3189 // FIXME: this might strip inner qualifiers; okay?
3190 const ReferenceType *T = this;
3191 while (T->isInnerRef())
3192 T = T->PointeeType->castAs<ReferenceType>();
3193 return T->PointeeType;
3194 }
3195
3196 void Profile(llvm::FoldingSetNodeID &ID) {
3197 Profile(ID, PointeeType, isSpelledAsLValue());
3198 }
3199
3200 static void Profile(llvm::FoldingSetNodeID &ID,
3201 QualType Referencee,
3202 bool SpelledAsLValue) {
3203 ID.AddPointer(Ptr: Referencee.getAsOpaquePtr());
3204 ID.AddBoolean(B: SpelledAsLValue);
3205 }
3206
3207 static bool classof(const Type *T) {
3208 return T->getTypeClass() == LValueReference ||
3209 T->getTypeClass() == RValueReference;
3210 }
3211};
3212
3213/// An lvalue reference type, per C++11 [dcl.ref].
3214class LValueReferenceType : public ReferenceType {
3215 friend class ASTContext; // ASTContext creates these
3216
3217 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
3218 bool SpelledAsLValue)
3219 : ReferenceType(LValueReference, Referencee, CanonicalRef,
3220 SpelledAsLValue) {}
3221
3222public:
3223 bool isSugared() const { return false; }
3224 QualType desugar() const { return QualType(this, 0); }
3225
3226 static bool classof(const Type *T) {
3227 return T->getTypeClass() == LValueReference;
3228 }
3229};
3230
3231/// An rvalue reference type, per C++11 [dcl.ref].
3232class RValueReferenceType : public ReferenceType {
3233 friend class ASTContext; // ASTContext creates these
3234
3235 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
3236 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
3237
3238public:
3239 bool isSugared() const { return false; }
3240 QualType desugar() const { return QualType(this, 0); }
3241
3242 static bool classof(const Type *T) {
3243 return T->getTypeClass() == RValueReference;
3244 }
3245};
3246
3247/// A pointer to member type per C++ 8.3.3 - Pointers to members.
3248///
3249/// This includes both pointers to data members and pointer to member functions.
3250class MemberPointerType : public Type, public llvm::FoldingSetNode {
3251 friend class ASTContext; // ASTContext creates these.
3252
3253 QualType PointeeType;
3254
3255 /// The class of which the pointee is a member. Must ultimately be a
3256 /// RecordType, but could be a typedef or a template parameter too.
3257 const Type *Class;
3258
3259 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
3260 : Type(MemberPointer, CanonicalPtr,
3261 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
3262 Pointee->getDependence()),
3263 PointeeType(Pointee), Class(Cls) {}
3264
3265public:
3266 QualType getPointeeType() const { return PointeeType; }
3267
3268 /// Returns true if the member type (i.e. the pointee type) is a
3269 /// function type rather than a data-member type.
3270 bool isMemberFunctionPointer() const {
3271 return PointeeType->isFunctionProtoType();
3272 }
3273
3274 /// Returns true if the member type (i.e. the pointee type) is a
3275 /// data type rather than a function type.
3276 bool isMemberDataPointer() const {
3277 return !PointeeType->isFunctionProtoType();
3278 }
3279
3280 const Type *getClass() const { return Class; }
3281 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
3282
3283 bool isSugared() const { return false; }
3284 QualType desugar() const { return QualType(this, 0); }
3285
3286 void Profile(llvm::FoldingSetNodeID &ID) {
3287 Profile(ID, Pointee: getPointeeType(), Class: getClass());
3288 }
3289
3290 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
3291 const Type *Class) {
3292 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
3293 ID.AddPointer(Ptr: Class);
3294 }
3295
3296 static bool classof(const Type *T) {
3297 return T->getTypeClass() == MemberPointer;
3298 }
3299};
3300
3301/// Capture whether this is a normal array (e.g. int X[4])
3302/// an array with a static size (e.g. int X[static 4]), or an array
3303/// with a star size (e.g. int X[*]).
3304/// 'static' is only allowed on function parameters.
3305enum class ArraySizeModifier { Normal, Static, Star };
3306
3307/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
3308class ArrayType : public Type, public llvm::FoldingSetNode {
3309private:
3310 /// The element type of the array.
3311 QualType ElementType;
3312
3313protected:
3314 friend class ASTContext; // ASTContext creates these.
3315
3316 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
3317 unsigned tq, const Expr *sz = nullptr);
3318
3319public:
3320 QualType getElementType() const { return ElementType; }
3321
3322 ArraySizeModifier getSizeModifier() const {
3323 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
3324 }
3325
3326 Qualifiers getIndexTypeQualifiers() const {
3327 return Qualifiers::fromCVRMask(CVR: getIndexTypeCVRQualifiers());
3328 }
3329
3330 unsigned getIndexTypeCVRQualifiers() const {
3331 return ArrayTypeBits.IndexTypeQuals;
3332 }
3333
3334 static bool classof(const Type *T) {
3335 return T->getTypeClass() == ConstantArray ||
3336 T->getTypeClass() == VariableArray ||
3337 T->getTypeClass() == IncompleteArray ||
3338 T->getTypeClass() == DependentSizedArray ||
3339 T->getTypeClass() == ArrayParameter;
3340 }
3341};
3342
3343/// Represents the canonical version of C arrays with a specified constant size.
3344/// For example, the canonical type for 'int A[4 + 4*100]' is a
3345/// ConstantArrayType where the element type is 'int' and the size is 404.
3346class ConstantArrayType : public ArrayType {
3347 friend class ASTContext; // ASTContext creates these.
3348
3349 struct ExternalSize {
3350 ExternalSize(const llvm::APInt &Sz, const Expr *SE)
3351 : Size(Sz), SizeExpr(SE) {}
3352 llvm::APInt Size; // Allows us to unique the type.
3353 const Expr *SizeExpr;
3354 };
3355
3356 union {
3357 uint64_t Size;
3358 ExternalSize *SizePtr;
3359 };
3360
3361 ConstantArrayType(QualType Et, QualType Can, uint64_t Width, uint64_t Sz,
3362 ArraySizeModifier SM, unsigned TQ)
3363 : ArrayType(ConstantArray, Et, Can, SM, TQ, nullptr), Size(Sz) {
3364 ConstantArrayTypeBits.HasExternalSize = false;
3365 ConstantArrayTypeBits.SizeWidth = Width / 8;
3366 // The in-structure size stores the size in bytes rather than bits so we
3367 // drop the three least significant bits since they're always zero anyways.
3368 assert(Width < 0xFF && "Type width in bits must be less than 8 bits");
3369 }
3370
3371 ConstantArrayType(QualType Et, QualType Can, ExternalSize *SzPtr,
3372 ArraySizeModifier SM, unsigned TQ)
3373 : ArrayType(ConstantArray, Et, Can, SM, TQ, SzPtr->SizeExpr),
3374 SizePtr(SzPtr) {
3375 ConstantArrayTypeBits.HasExternalSize = true;
3376 ConstantArrayTypeBits.SizeWidth = 0;
3377
3378 assert((SzPtr->SizeExpr == nullptr || !Can.isNull()) &&
3379 "canonical constant array should not have size expression");
3380 }
3381
3382 static ConstantArrayType *Create(const ASTContext &Ctx, QualType ET,
3383 QualType Can, const llvm::APInt &Sz,
3384 const Expr *SzExpr, ArraySizeModifier SzMod,
3385 unsigned Qual);
3386
3387protected:
3388 ConstantArrayType(TypeClass Tc, const ConstantArrayType *ATy, QualType Can)
3389 : ArrayType(Tc, ATy->getElementType(), Can, ATy->getSizeModifier(),
3390 ATy->getIndexTypeQualifiers().getAsOpaqueValue(), nullptr) {
3391 ConstantArrayTypeBits.HasExternalSize =
3392 ATy->ConstantArrayTypeBits.HasExternalSize;
3393 if (!ConstantArrayTypeBits.HasExternalSize) {
3394 ConstantArrayTypeBits.SizeWidth = ATy->ConstantArrayTypeBits.SizeWidth;
3395 Size = ATy->Size;
3396 } else
3397 SizePtr = ATy->SizePtr;
3398 }
3399
3400public:
3401 /// Return the constant array size as an APInt.
3402 llvm::APInt getSize() const {
3403 return ConstantArrayTypeBits.HasExternalSize
3404 ? SizePtr->Size
3405 : llvm::APInt(ConstantArrayTypeBits.SizeWidth * 8, Size);
3406 }
3407
3408 /// Return the bit width of the size type.
3409 unsigned getSizeBitWidth() const {
3410 return ConstantArrayTypeBits.HasExternalSize
3411 ? SizePtr->Size.getBitWidth()
3412 : static_cast<unsigned>(ConstantArrayTypeBits.SizeWidth * 8);
3413 }
3414
3415 /// Return true if the size is zero.
3416 bool isZeroSize() const {
3417 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.isZero()
3418 : 0 == Size;
3419 }
3420
3421 /// Return the size zero-extended as a uint64_t.
3422 uint64_t getZExtSize() const {
3423 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.getZExtValue()
3424 : Size;
3425 }
3426
3427 /// Return the size sign-extended as a uint64_t.
3428 int64_t getSExtSize() const {
3429 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.getSExtValue()
3430 : static_cast<int64_t>(Size);
3431 }
3432
3433 /// Return the size zero-extended to uint64_t or UINT64_MAX if the value is
3434 /// larger than UINT64_MAX.
3435 uint64_t getLimitedSize() const {
3436 return ConstantArrayTypeBits.HasExternalSize
3437 ? SizePtr->Size.getLimitedValue()
3438 : Size;
3439 }
3440
3441 /// Return a pointer to the size expression.
3442 const Expr *getSizeExpr() const {
3443 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->SizeExpr : nullptr;
3444 }
3445
3446 bool isSugared() const { return false; }
3447 QualType desugar() const { return QualType(this, 0); }
3448
3449 /// Determine the number of bits required to address a member of
3450 // an array with the given element type and number of elements.
3451 static unsigned getNumAddressingBits(const ASTContext &Context,
3452 QualType ElementType,
3453 const llvm::APInt &NumElements);
3454
3455 unsigned getNumAddressingBits(const ASTContext &Context) const;
3456
3457 /// Determine the maximum number of active bits that an array's size
3458 /// can require, which limits the maximum size of the array.
3459 static unsigned getMaxSizeBits(const ASTContext &Context);
3460
3461 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3462 Profile(ID, Ctx, getElementType(), getZExtSize(), getSizeExpr(),
3463 getSizeModifier(), getIndexTypeCVRQualifiers());
3464 }
3465
3466 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
3467 QualType ET, uint64_t ArraySize, const Expr *SizeExpr,
3468 ArraySizeModifier SizeMod, unsigned TypeQuals);
3469
3470 static bool classof(const Type *T) {
3471 return T->getTypeClass() == ConstantArray ||
3472 T->getTypeClass() == ArrayParameter;
3473 }
3474};
3475
3476/// Represents a constant array type that does not decay to a pointer when used
3477/// as a function parameter.
3478class ArrayParameterType : public ConstantArrayType {
3479 friend class ASTContext; // ASTContext creates these.
3480
3481 ArrayParameterType(const ConstantArrayType *ATy, QualType CanTy)
3482 : ConstantArrayType(ArrayParameter, ATy, CanTy) {}
3483
3484public:
3485 static bool classof(const Type *T) {
3486 return T->getTypeClass() == ArrayParameter;
3487 }
3488};
3489
3490/// Represents a C array with an unspecified size. For example 'int A[]' has
3491/// an IncompleteArrayType where the element type is 'int' and the size is
3492/// unspecified.
3493class IncompleteArrayType : public ArrayType {
3494 friend class ASTContext; // ASTContext creates these.
3495
3496 IncompleteArrayType(QualType et, QualType can,
3497 ArraySizeModifier sm, unsigned tq)
3498 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3499
3500public:
3501 friend class StmtIteratorBase;
3502
3503 bool isSugared() const { return false; }
3504 QualType desugar() const { return QualType(this, 0); }
3505
3506 static bool classof(const Type *T) {
3507 return T->getTypeClass() == IncompleteArray;
3508 }
3509
3510 void Profile(llvm::FoldingSetNodeID &ID) {
3511 Profile(ID, getElementType(), getSizeModifier(),
3512 getIndexTypeCVRQualifiers());
3513 }
3514
3515 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3516 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3517 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
3518 ID.AddInteger(llvm::to_underlying(SizeMod));
3519 ID.AddInteger(I: TypeQuals);
3520 }
3521};
3522
3523/// Represents a C array with a specified size that is not an
3524/// integer-constant-expression. For example, 'int s[x+foo()]'.
3525/// Since the size expression is an arbitrary expression, we store it as such.
3526///
3527/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3528/// should not be: two lexically equivalent variable array types could mean
3529/// different things, for example, these variables do not have the same type
3530/// dynamically:
3531///
3532/// void foo(int x) {
3533/// int Y[x];
3534/// ++x;
3535/// int Z[x];
3536/// }
3537class VariableArrayType : public ArrayType {
3538 friend class ASTContext; // ASTContext creates these.
3539
3540 /// An assignment-expression. VLA's are only permitted within
3541 /// a function block.
3542 Stmt *SizeExpr;
3543
3544 /// The range spanned by the left and right array brackets.
3545 SourceRange Brackets;
3546
3547 VariableArrayType(QualType et, QualType can, Expr *e,
3548 ArraySizeModifier sm, unsigned tq,
3549 SourceRange brackets)
3550 : ArrayType(VariableArray, et, can, sm, tq, e),
3551 SizeExpr((Stmt*) e), Brackets(brackets) {}
3552
3553public:
3554 friend class StmtIteratorBase;
3555
3556 Expr *getSizeExpr() const {
3557 // We use C-style casts instead of cast<> here because we do not wish
3558 // to have a dependency of Type.h on Stmt.h/Expr.h.
3559 return (Expr*) SizeExpr;
3560 }
3561
3562 SourceRange getBracketsRange() const { return Brackets; }
3563 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3564 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3565
3566 bool isSugared() const { return false; }
3567 QualType desugar() const { return QualType(this, 0); }
3568
3569 static bool classof(const Type *T) {
3570 return T->getTypeClass() == VariableArray;
3571 }
3572
3573 void Profile(llvm::FoldingSetNodeID &ID) {
3574 llvm_unreachable("Cannot unique VariableArrayTypes.");
3575 }
3576};
3577
3578/// Represents an array type in C++ whose size is a value-dependent expression.
3579///
3580/// For example:
3581/// \code
3582/// template<typename T, int Size>
3583/// class array {
3584/// T data[Size];
3585/// };
3586/// \endcode
3587///
3588/// For these types, we won't actually know what the array bound is
3589/// until template instantiation occurs, at which point this will
3590/// become either a ConstantArrayType or a VariableArrayType.
3591class DependentSizedArrayType : public ArrayType {
3592 friend class ASTContext; // ASTContext creates these.
3593
3594 /// An assignment expression that will instantiate to the
3595 /// size of the array.
3596 ///
3597 /// The expression itself might be null, in which case the array
3598 /// type will have its size deduced from an initializer.
3599 Stmt *SizeExpr;
3600
3601 /// The range spanned by the left and right array brackets.
3602 SourceRange Brackets;
3603
3604 DependentSizedArrayType(QualType et, QualType can, Expr *e,
3605 ArraySizeModifier sm, unsigned tq,
3606 SourceRange brackets);
3607
3608public:
3609 friend class StmtIteratorBase;
3610
3611 Expr *getSizeExpr() const {
3612 // We use C-style casts instead of cast<> here because we do not wish
3613 // to have a dependency of Type.h on Stmt.h/Expr.h.
3614 return (Expr*) SizeExpr;
3615 }
3616
3617 SourceRange getBracketsRange() const { return Brackets; }
3618 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3619 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3620
3621 bool isSugared() const { return false; }
3622 QualType desugar() const { return QualType(this, 0); }
3623
3624 static bool classof(const Type *T) {
3625 return T->getTypeClass() == DependentSizedArray;
3626 }
3627
3628 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3629 Profile(ID, Context, getElementType(),
3630 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3631 }
3632
3633 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3634 QualType ET, ArraySizeModifier SizeMod,
3635 unsigned TypeQuals, Expr *E);
3636};
3637
3638/// Represents an extended address space qualifier where the input address space
3639/// value is dependent. Non-dependent address spaces are not represented with a
3640/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3641///
3642/// For example:
3643/// \code
3644/// template<typename T, int AddrSpace>
3645/// class AddressSpace {
3646/// typedef T __attribute__((address_space(AddrSpace))) type;
3647/// }
3648/// \endcode
3649class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3650 friend class ASTContext;
3651
3652 Expr *AddrSpaceExpr;
3653 QualType PointeeType;
3654 SourceLocation loc;
3655
3656 DependentAddressSpaceType(QualType PointeeType, QualType can,
3657 Expr *AddrSpaceExpr, SourceLocation loc);
3658
3659public:
3660 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3661 QualType getPointeeType() const { return PointeeType; }
3662 SourceLocation getAttributeLoc() const { return loc; }
3663
3664 bool isSugared() const { return false; }
3665 QualType desugar() const { return QualType(this, 0); }
3666
3667 static bool classof(const Type *T) {
3668 return T->getTypeClass() == DependentAddressSpace;
3669 }
3670
3671 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3672 Profile(ID, Context, PointeeType: getPointeeType(), AddrSpaceExpr: getAddrSpaceExpr());
3673 }
3674
3675 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3676 QualType PointeeType, Expr *AddrSpaceExpr);
3677};
3678
3679/// Represents an extended vector type where either the type or size is
3680/// dependent.
3681///
3682/// For example:
3683/// \code
3684/// template<typename T, int Size>
3685/// class vector {
3686/// typedef T __attribute__((ext_vector_type(Size))) type;
3687/// }
3688/// \endcode
3689class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3690 friend class ASTContext;
3691
3692 Expr *SizeExpr;
3693
3694 /// The element type of the array.
3695 QualType ElementType;
3696
3697 SourceLocation loc;
3698
3699 DependentSizedExtVectorType(QualType ElementType, QualType can,
3700 Expr *SizeExpr, SourceLocation loc);
3701
3702public:
3703 Expr *getSizeExpr() const { return SizeExpr; }
3704 QualType getElementType() const { return ElementType; }
3705 SourceLocation getAttributeLoc() const { return loc; }
3706
3707 bool isSugared() const { return false; }
3708 QualType desugar() const { return QualType(this, 0); }
3709
3710 static bool classof(const Type *T) {
3711 return T->getTypeClass() == DependentSizedExtVector;
3712 }
3713
3714 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3715 Profile(ID, Context, ElementType: getElementType(), SizeExpr: getSizeExpr());
3716 }
3717
3718 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3719 QualType ElementType, Expr *SizeExpr);
3720};
3721
3722enum class VectorKind {
3723 /// not a target-specific vector type
3724 Generic,
3725
3726 /// is AltiVec vector
3727 AltiVecVector,
3728
3729 /// is AltiVec 'vector Pixel'
3730 AltiVecPixel,
3731
3732 /// is AltiVec 'vector bool ...'
3733 AltiVecBool,
3734
3735 /// is ARM Neon vector
3736 Neon,
3737
3738 /// is ARM Neon polynomial vector
3739 NeonPoly,
3740
3741 /// is AArch64 SVE fixed-length data vector
3742 SveFixedLengthData,
3743
3744 /// is AArch64 SVE fixed-length predicate vector
3745 SveFixedLengthPredicate,
3746
3747 /// is RISC-V RVV fixed-length data vector
3748 RVVFixedLengthData,
3749
3750 /// is RISC-V RVV fixed-length mask vector
3751 RVVFixedLengthMask,
3752};
3753
3754/// Represents a GCC generic vector type. This type is created using
3755/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3756/// bytes; or from an Altivec __vector or vector declaration.
3757/// Since the constructor takes the number of vector elements, the
3758/// client is responsible for converting the size into the number of elements.
3759class VectorType : public Type, public llvm::FoldingSetNode {
3760protected:
3761 friend class ASTContext; // ASTContext creates these.
3762
3763 /// The element type of the vector.
3764 QualType ElementType;
3765
3766 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3767 VectorKind vecKind);
3768
3769 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3770 QualType canonType, VectorKind vecKind);
3771
3772public:
3773 QualType getElementType() const { return ElementType; }
3774 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3775
3776 bool isSugared() const { return false; }
3777 QualType desugar() const { return QualType(this, 0); }
3778
3779 VectorKind getVectorKind() const {
3780 return VectorKind(VectorTypeBits.VecKind);
3781 }
3782
3783 void Profile(llvm::FoldingSetNodeID &ID) {
3784 Profile(ID, getElementType(), getNumElements(),
3785 getTypeClass(), getVectorKind());
3786 }
3787
3788 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3789 unsigned NumElements, TypeClass TypeClass,
3790 VectorKind VecKind) {
3791 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
3792 ID.AddInteger(I: NumElements);
3793 ID.AddInteger(I: TypeClass);
3794 ID.AddInteger(llvm::to_underlying(VecKind));
3795 }
3796
3797 static bool classof(const Type *T) {
3798 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3799 }
3800};
3801
3802/// Represents a vector type where either the type or size is dependent.
3803////
3804/// For example:
3805/// \code
3806/// template<typename T, int Size>
3807/// class vector {
3808/// typedef T __attribute__((vector_size(Size))) type;
3809/// }
3810/// \endcode
3811class DependentVectorType : public Type, public llvm::FoldingSetNode {
3812 friend class ASTContext;
3813
3814 QualType ElementType;
3815 Expr *SizeExpr;
3816 SourceLocation Loc;
3817
3818 DependentVectorType(QualType ElementType, QualType CanonType, Expr *SizeExpr,
3819 SourceLocation Loc, VectorKind vecKind);
3820
3821public:
3822 Expr *getSizeExpr() const { return SizeExpr; }
3823 QualType getElementType() const { return ElementType; }
3824 SourceLocation getAttributeLoc() const { return Loc; }
3825 VectorKind getVectorKind() const {
3826 return VectorKind(VectorTypeBits.VecKind);
3827 }
3828
3829 bool isSugared() const { return false; }
3830 QualType desugar() const { return QualType(this, 0); }
3831
3832 static bool classof(const Type *T) {
3833 return T->getTypeClass() == DependentVector;
3834 }
3835
3836 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3837 Profile(ID, Context, ElementType: getElementType(), SizeExpr: getSizeExpr(), VecKind: getVectorKind());
3838 }
3839
3840 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3841 QualType ElementType, const Expr *SizeExpr,
3842 VectorKind VecKind);
3843};
3844
3845/// ExtVectorType - Extended vector type. This type is created using
3846/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3847/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3848/// class enables syntactic extensions, like Vector Components for accessing
3849/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3850/// Shading Language).
3851class ExtVectorType : public VectorType {
3852 friend class ASTContext; // ASTContext creates these.
3853
3854 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3855 : VectorType(ExtVector, vecType, nElements, canonType,
3856 VectorKind::Generic) {}
3857
3858public:
3859 static int getPointAccessorIdx(char c) {
3860 switch (c) {
3861 default: return -1;
3862 case 'x': case 'r': return 0;
3863 case 'y': case 'g': return 1;
3864 case 'z': case 'b': return 2;
3865 case 'w': case 'a': return 3;
3866 }
3867 }
3868
3869 static int getNumericAccessorIdx(char c) {
3870 switch (c) {
3871 default: return -1;
3872 case '0': return 0;
3873 case '1': return 1;
3874 case '2': return 2;
3875 case '3': return 3;
3876 case '4': return 4;
3877 case '5': return 5;
3878 case '6': return 6;
3879 case '7': return 7;
3880 case '8': return 8;
3881 case '9': return 9;
3882 case 'A':
3883 case 'a': return 10;
3884 case 'B':
3885 case 'b': return 11;
3886 case 'C':
3887 case 'c': return 12;
3888 case 'D':
3889 case 'd': return 13;
3890 case 'E':
3891 case 'e': return 14;
3892 case 'F':
3893 case 'f': return 15;
3894 }
3895 }
3896
3897 static int getAccessorIdx(char c, bool isNumericAccessor) {
3898 if (isNumericAccessor)
3899 return getNumericAccessorIdx(c);
3900 else
3901 return getPointAccessorIdx(c);
3902 }
3903
3904 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3905 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3906 return unsigned(idx-1) < getNumElements();
3907 return false;
3908 }
3909
3910 bool isSugared() const { return false; }
3911 QualType desugar() const { return QualType(this, 0); }
3912
3913 static bool classof(const Type *T) {
3914 return T->getTypeClass() == ExtVector;
3915 }
3916};
3917
3918/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3919/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3920/// number of rows and "columns" specifies the number of columns.
3921class MatrixType : public Type, public llvm::FoldingSetNode {
3922protected:
3923 friend class ASTContext;
3924
3925 /// The element type of the matrix.
3926 QualType ElementType;
3927
3928 MatrixType(QualType ElementTy, QualType CanonElementTy);
3929
3930 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3931 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3932
3933public:
3934 /// Returns type of the elements being stored in the matrix
3935 QualType getElementType() const { return ElementType; }
3936
3937 /// Valid elements types are the following:
3938 /// * an integer type (as in C23 6.2.5p22), but excluding enumerated types
3939 /// and _Bool
3940 /// * the standard floating types float or double
3941 /// * a half-precision floating point type, if one is supported on the target
3942 static bool isValidElementType(QualType T) {
3943 return T->isDependentType() ||
3944 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3945 }
3946
3947 bool isSugared() const { return false; }
3948 QualType desugar() const { return QualType(this, 0); }
3949
3950 static bool classof(const Type *T) {
3951 return T->getTypeClass() == ConstantMatrix ||
3952 T->getTypeClass() == DependentSizedMatrix;
3953 }
3954};
3955
3956/// Represents a concrete matrix type with constant number of rows and columns
3957class ConstantMatrixType final : public MatrixType {
3958protected:
3959 friend class ASTContext;
3960
3961 /// Number of rows and columns.
3962 unsigned NumRows;
3963 unsigned NumColumns;
3964
3965 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3966
3967 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3968 unsigned NColumns, QualType CanonElementType);
3969
3970 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3971 unsigned NColumns, QualType CanonElementType);
3972
3973public:
3974 /// Returns the number of rows in the matrix.
3975 unsigned getNumRows() const { return NumRows; }
3976
3977 /// Returns the number of columns in the matrix.
3978 unsigned getNumColumns() const { return NumColumns; }
3979
3980 /// Returns the number of elements required to embed the matrix into a vector.
3981 unsigned getNumElementsFlattened() const {
3982 return getNumRows() * getNumColumns();
3983 }
3984
3985 /// Returns true if \p NumElements is a valid matrix dimension.
3986 static constexpr bool isDimensionValid(size_t NumElements) {
3987 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3988 }
3989
3990 /// Returns the maximum number of elements per dimension.
3991 static constexpr unsigned getMaxElementsPerDimension() {
3992 return MaxElementsPerDimension;
3993 }
3994
3995 void Profile(llvm::FoldingSetNodeID &ID) {
3996 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3997 getTypeClass());
3998 }
3999
4000 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
4001 unsigned NumRows, unsigned NumColumns,
4002 TypeClass TypeClass) {
4003 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
4004 ID.AddInteger(I: NumRows);
4005 ID.AddInteger(I: NumColumns);
4006 ID.AddInteger(I: TypeClass);
4007 }
4008
4009 static bool classof(const Type *T) {
4010 return T->getTypeClass() == ConstantMatrix;
4011 }
4012};
4013
4014/// Represents a matrix type where the type and the number of rows and columns
4015/// is dependent on a template.
4016class DependentSizedMatrixType final : public MatrixType {
4017 friend class ASTContext;
4018
4019 Expr *RowExpr;
4020 Expr *ColumnExpr;
4021
4022 SourceLocation loc;
4023
4024 DependentSizedMatrixType(QualType ElementType, QualType CanonicalType,
4025 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc);
4026
4027public:
4028 Expr *getRowExpr() const { return RowExpr; }
4029 Expr *getColumnExpr() const { return ColumnExpr; }
4030 SourceLocation getAttributeLoc() const { return loc; }
4031
4032 static bool classof(const Type *T) {
4033 return T->getTypeClass() == DependentSizedMatrix;
4034 }
4035
4036 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4037 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
4038 }
4039
4040 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4041 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
4042};
4043
4044/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
4045/// class of FunctionNoProtoType and FunctionProtoType.
4046class FunctionType : public Type {
4047 // The type returned by the function.
4048 QualType ResultType;
4049
4050public:
4051 /// Interesting information about a specific parameter that can't simply
4052 /// be reflected in parameter's type. This is only used by FunctionProtoType
4053 /// but is in FunctionType to make this class available during the
4054 /// specification of the bases of FunctionProtoType.
4055 ///
4056 /// It makes sense to model language features this way when there's some
4057 /// sort of parameter-specific override (such as an attribute) that
4058 /// affects how the function is called. For example, the ARC ns_consumed
4059 /// attribute changes whether a parameter is passed at +0 (the default)
4060 /// or +1 (ns_consumed). This must be reflected in the function type,
4061 /// but isn't really a change to the parameter type.
4062 ///
4063 /// One serious disadvantage of modelling language features this way is
4064 /// that they generally do not work with language features that attempt
4065 /// to destructure types. For example, template argument deduction will
4066 /// not be able to match a parameter declared as
4067 /// T (*)(U)
4068 /// against an argument of type
4069 /// void (*)(__attribute__((ns_consumed)) id)
4070 /// because the substitution of T=void, U=id into the former will
4071 /// not produce the latter.
4072 class ExtParameterInfo {
4073 enum {
4074 ABIMask = 0x0F,
4075 IsConsumed = 0x10,
4076 HasPassObjSize = 0x20,
4077 IsNoEscape = 0x40,
4078 };
4079 unsigned char Data = 0;
4080
4081 public:
4082 ExtParameterInfo() = default;
4083
4084 /// Return the ABI treatment of this parameter.
4085 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
4086 ExtParameterInfo withABI(ParameterABI kind) const {
4087 ExtParameterInfo copy = *this;
4088 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
4089 return copy;
4090 }
4091
4092 /// Is this parameter considered "consumed" by Objective-C ARC?
4093 /// Consumed parameters must have retainable object type.
4094 bool isConsumed() const { return (Data & IsConsumed); }
4095 ExtParameterInfo withIsConsumed(bool consumed) const {
4096 ExtParameterInfo copy = *this;
4097 if (consumed)
4098 copy.Data |= IsConsumed;
4099 else
4100 copy.Data &= ~IsConsumed;
4101 return copy;
4102 }
4103
4104 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
4105 ExtParameterInfo withHasPassObjectSize() const {
4106 ExtParameterInfo Copy = *this;
4107 Copy.Data |= HasPassObjSize;
4108 return Copy;
4109 }
4110
4111 bool isNoEscape() const { return Data & IsNoEscape; }
4112 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
4113 ExtParameterInfo Copy = *this;
4114 if (NoEscape)
4115 Copy.Data |= IsNoEscape;
4116 else
4117 Copy.Data &= ~IsNoEscape;
4118 return Copy;
4119 }
4120
4121 unsigned char getOpaqueValue() const { return Data; }
4122 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
4123 ExtParameterInfo result;
4124 result.Data = data;
4125 return result;
4126 }
4127
4128 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
4129 return lhs.Data == rhs.Data;
4130 }
4131
4132 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
4133 return lhs.Data != rhs.Data;
4134 }
4135 };
4136
4137 /// A class which abstracts out some details necessary for
4138 /// making a call.
4139 ///
4140 /// It is not actually used directly for storing this information in
4141 /// a FunctionType, although FunctionType does currently use the
4142 /// same bit-pattern.
4143 ///
4144 // If you add a field (say Foo), other than the obvious places (both,
4145 // constructors, compile failures), what you need to update is
4146 // * Operator==
4147 // * getFoo
4148 // * withFoo
4149 // * functionType. Add Foo, getFoo.
4150 // * ASTContext::getFooType
4151 // * ASTContext::mergeFunctionTypes
4152 // * FunctionNoProtoType::Profile
4153 // * FunctionProtoType::Profile
4154 // * TypePrinter::PrintFunctionProto
4155 // * AST read and write
4156 // * Codegen
4157 class ExtInfo {
4158 friend class FunctionType;
4159
4160 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
4161 // adjust the Bits field below, and if you add bits, you'll need to adjust
4162 // Type::FunctionTypeBitfields::ExtInfo as well.
4163
4164 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
4165 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
4166 //
4167 // regparm is either 0 (no regparm attribute) or the regparm value+1.
4168 enum { CallConvMask = 0x1F };
4169 enum { NoReturnMask = 0x20 };
4170 enum { ProducesResultMask = 0x40 };
4171 enum { NoCallerSavedRegsMask = 0x80 };
4172 enum {
4173 RegParmMask = 0x700,
4174 RegParmOffset = 8
4175 };
4176 enum { NoCfCheckMask = 0x800 };
4177 enum { CmseNSCallMask = 0x1000 };
4178 uint16_t Bits = CC_C;
4179
4180 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
4181
4182 public:
4183 // Constructor with no defaults. Use this when you know that you
4184 // have all the elements (when reading an AST file for example).
4185 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
4186 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
4187 bool cmseNSCall) {
4188 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
4189 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
4190 (producesResult ? ProducesResultMask : 0) |
4191 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
4192 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
4193 (NoCfCheck ? NoCfCheckMask : 0) |
4194 (cmseNSCall ? CmseNSCallMask : 0);
4195 }
4196
4197 // Constructor with all defaults. Use when for example creating a
4198 // function known to use defaults.
4199 ExtInfo() = default;
4200
4201 // Constructor with just the calling convention, which is an important part
4202 // of the canonical type.
4203 ExtInfo(CallingConv CC) : Bits(CC) {}
4204
4205 bool getNoReturn() const { return Bits & NoReturnMask; }
4206 bool getProducesResult() const { return Bits & ProducesResultMask; }
4207 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
4208 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
4209 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
4210 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
4211
4212 unsigned getRegParm() const {
4213 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
4214 if (RegParm > 0)
4215 --RegParm;
4216 return RegParm;
4217 }
4218
4219 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
4220
4221 bool operator==(ExtInfo Other) const {
4222 return Bits == Other.Bits;
4223 }
4224 bool operator!=(ExtInfo Other) const {
4225 return Bits != Other.Bits;
4226 }
4227
4228 // Note that we don't have setters. That is by design, use
4229 // the following with methods instead of mutating these objects.
4230
4231 ExtInfo withNoReturn(bool noReturn) const {
4232 if (noReturn)
4233 return ExtInfo(Bits | NoReturnMask);
4234 else
4235 return ExtInfo(Bits & ~NoReturnMask);
4236 }
4237
4238 ExtInfo withProducesResult(bool producesResult) const {
4239 if (producesResult)
4240 return ExtInfo(Bits | ProducesResultMask);
4241 else
4242 return ExtInfo(Bits & ~ProducesResultMask);
4243 }
4244
4245 ExtInfo withCmseNSCall(bool cmseNSCall) const {
4246 if (cmseNSCall)
4247 return ExtInfo(Bits | CmseNSCallMask);
4248 else
4249 return ExtInfo(Bits & ~CmseNSCallMask);
4250 }
4251
4252 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
4253 if (noCallerSavedRegs)
4254 return ExtInfo(Bits | NoCallerSavedRegsMask);
4255 else
4256 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
4257 }
4258
4259 ExtInfo withNoCfCheck(bool noCfCheck) const {
4260 if (noCfCheck)
4261 return ExtInfo(Bits | NoCfCheckMask);
4262 else
4263 return ExtInfo(Bits & ~NoCfCheckMask);
4264 }
4265
4266 ExtInfo withRegParm(unsigned RegParm) const {
4267 assert(RegParm < 7 && "Invalid regparm value");
4268 return ExtInfo((Bits & ~RegParmMask) |
4269 ((RegParm + 1) << RegParmOffset));
4270 }
4271
4272 ExtInfo withCallingConv(CallingConv cc) const {
4273 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
4274 }
4275
4276 void Profile(llvm::FoldingSetNodeID &ID) const {
4277 ID.AddInteger(I: Bits);
4278 }
4279 };
4280
4281 /// A simple holder for a QualType representing a type in an
4282 /// exception specification. Unfortunately needed by FunctionProtoType
4283 /// because TrailingObjects cannot handle repeated types.
4284 struct ExceptionType { QualType Type; };
4285
4286 /// A simple holder for various uncommon bits which do not fit in
4287 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
4288 /// alignment of subsequent objects in TrailingObjects.
4289 struct alignas(void *) FunctionTypeExtraBitfields {
4290 /// The number of types in the exception specification.
4291 /// A whole unsigned is not needed here and according to
4292 /// [implimits] 8 bits would be enough here.
4293 unsigned NumExceptionType : 10;
4294
4295 LLVM_PREFERRED_TYPE(bool)
4296 unsigned HasArmTypeAttributes : 1;
4297
4298 FunctionTypeExtraBitfields()
4299 : NumExceptionType(0), HasArmTypeAttributes(false) {}
4300 };
4301
4302 /// The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number
4303 /// of function type attributes that can be set on function types, including
4304 /// function pointers.
4305 enum AArch64SMETypeAttributes : unsigned {
4306 SME_NormalFunction = 0,
4307 SME_PStateSMEnabledMask = 1 << 0,
4308 SME_PStateSMCompatibleMask = 1 << 1,
4309
4310 // Describes the value of the state using ArmStateValue.
4311 SME_ZAShift = 2,
4312 SME_ZAMask = 0b111 << SME_ZAShift,
4313 SME_ZT0Shift = 5,
4314 SME_ZT0Mask = 0b111 << SME_ZT0Shift,
4315
4316 SME_AttributeMask =
4317 0b111'111'11 // We can't support more than 8 bits because of
4318 // the bitmask in FunctionTypeExtraBitfields.
4319 };
4320
4321 enum ArmStateValue : unsigned {
4322 ARM_None = 0,
4323 ARM_Preserves = 1,
4324 ARM_In = 2,
4325 ARM_Out = 3,
4326 ARM_InOut = 4,
4327 };
4328
4329 static ArmStateValue getArmZAState(unsigned AttrBits) {
4330 return (ArmStateValue)((AttrBits & SME_ZAMask) >> SME_ZAShift);
4331 }
4332
4333 static ArmStateValue getArmZT0State(unsigned AttrBits) {
4334 return (ArmStateValue)((AttrBits & SME_ZT0Mask) >> SME_ZT0Shift);
4335 }
4336
4337 /// A holder for Arm type attributes as described in the Arm C/C++
4338 /// Language extensions which are not particularly common to all
4339 /// types and therefore accounted separately from FunctionTypeBitfields.
4340 struct alignas(void *) FunctionTypeArmAttributes {
4341 /// Any AArch64 SME ACLE type attributes that need to be propagated
4342 /// on declarations and function pointers.
4343 unsigned AArch64SMEAttributes : 8;
4344
4345 FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
4346 };
4347
4348protected:
4349 FunctionType(TypeClass tc, QualType res, QualType Canonical,
4350 TypeDependence Dependence, ExtInfo Info)
4351 : Type(tc, Canonical, Dependence), ResultType(res) {
4352 FunctionTypeBits.ExtInfo = Info.Bits;
4353 }
4354
4355 Qualifiers getFastTypeQuals() const {
4356 if (isFunctionProtoType())
4357 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
4358
4359 return Qualifiers();
4360 }
4361
4362public:
4363 QualType getReturnType() const { return ResultType; }
4364
4365 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
4366 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
4367
4368 /// Determine whether this function type includes the GNU noreturn
4369 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
4370 /// type.
4371 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
4372
4373 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
4374 CallingConv getCallConv() const { return getExtInfo().getCC(); }
4375 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
4376
4377 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
4378 "Const, volatile and restrict are assumed to be a subset of "
4379 "the fast qualifiers.");
4380
4381 bool isConst() const { return getFastTypeQuals().hasConst(); }
4382 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
4383 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
4384
4385 /// Determine the type of an expression that calls a function of
4386 /// this type.
4387 QualType getCallResultType(const ASTContext &Context) const {
4388 return getReturnType().getNonLValueExprType(Context);
4389 }
4390
4391 static StringRef getNameForCallConv(CallingConv CC);
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == FunctionNoProto ||
4395 T->getTypeClass() == FunctionProto;
4396 }
4397};
4398
4399/// Represents a K&R-style 'int foo()' function, which has
4400/// no information available about its arguments.
4401class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
4402 friend class ASTContext; // ASTContext creates these.
4403
4404 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
4405 : FunctionType(FunctionNoProto, Result, Canonical,
4406 Result->getDependence() &
4407 ~(TypeDependence::DependentInstantiation |
4408 TypeDependence::UnexpandedPack),
4409 Info) {}
4410
4411public:
4412 // No additional state past what FunctionType provides.
4413
4414 bool isSugared() const { return false; }
4415 QualType desugar() const { return QualType(this, 0); }
4416
4417 void Profile(llvm::FoldingSetNodeID &ID) {
4418 Profile(ID, getReturnType(), getExtInfo());
4419 }
4420
4421 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
4422 ExtInfo Info) {
4423 Info.Profile(ID);
4424 ID.AddPointer(Ptr: ResultType.getAsOpaquePtr());
4425 }
4426
4427 static bool classof(const Type *T) {
4428 return T->getTypeClass() == FunctionNoProto;
4429 }
4430};
4431
4432/// Represents a prototype with parameter type info, e.g.
4433/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
4434/// parameters, not as having a single void parameter. Such a type can have
4435/// an exception specification, but this specification is not part of the
4436/// canonical type. FunctionProtoType has several trailing objects, some of
4437/// which optional. For more information about the trailing objects see
4438/// the first comment inside FunctionProtoType.
4439class FunctionProtoType final
4440 : public FunctionType,
4441 public llvm::FoldingSetNode,
4442 private llvm::TrailingObjects<
4443 FunctionProtoType, QualType, SourceLocation,
4444 FunctionType::FunctionTypeExtraBitfields,
4445 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
4446 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
4447 friend class ASTContext; // ASTContext creates these.
4448 friend TrailingObjects;
4449
4450 // FunctionProtoType is followed by several trailing objects, some of
4451 // which optional. They are in order:
4452 //
4453 // * An array of getNumParams() QualType holding the parameter types.
4454 // Always present. Note that for the vast majority of FunctionProtoType,
4455 // these will be the only trailing objects.
4456 //
4457 // * Optionally if the function is variadic, the SourceLocation of the
4458 // ellipsis.
4459 //
4460 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
4461 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
4462 // a single FunctionTypeExtraBitfields. Present if and only if
4463 // hasExtraBitfields() is true.
4464 //
4465 // * Optionally exactly one of:
4466 // * an array of getNumExceptions() ExceptionType,
4467 // * a single Expr *,
4468 // * a pair of FunctionDecl *,
4469 // * a single FunctionDecl *
4470 // used to store information about the various types of exception
4471 // specification. See getExceptionSpecSize for the details.
4472 //
4473 // * Optionally an array of getNumParams() ExtParameterInfo holding
4474 // an ExtParameterInfo for each of the parameters. Present if and
4475 // only if hasExtParameterInfos() is true.
4476 //
4477 // * Optionally a Qualifiers object to represent extra qualifiers that can't
4478 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
4479 // if hasExtQualifiers() is true.
4480 //
4481 // The optional FunctionTypeExtraBitfields has to be before the data
4482 // related to the exception specification since it contains the number
4483 // of exception types.
4484 //
4485 // We put the ExtParameterInfos last. If all were equal, it would make
4486 // more sense to put these before the exception specification, because
4487 // it's much easier to skip past them compared to the elaborate switch
4488 // required to skip the exception specification. However, all is not
4489 // equal; ExtParameterInfos are used to model very uncommon features,
4490 // and it's better not to burden the more common paths.
4491
4492public:
4493 /// Holds information about the various types of exception specification.
4494 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
4495 /// used to group together the various bits of information about the
4496 /// exception specification.
4497 struct ExceptionSpecInfo {
4498 /// The kind of exception specification this is.
4499 ExceptionSpecificationType Type = EST_None;
4500
4501 /// Explicitly-specified list of exception types.
4502 ArrayRef<QualType> Exceptions;
4503
4504 /// Noexcept expression, if this is a computed noexcept specification.
4505 Expr *NoexceptExpr = nullptr;
4506
4507 /// The function whose exception specification this is, for
4508 /// EST_Unevaluated and EST_Uninstantiated.
4509 FunctionDecl *SourceDecl = nullptr;
4510
4511 /// The function template whose exception specification this is instantiated
4512 /// from, for EST_Uninstantiated.
4513 FunctionDecl *SourceTemplate = nullptr;
4514
4515 ExceptionSpecInfo() = default;
4516
4517 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
4518
4519 void instantiate();
4520 };
4521
4522 /// Extra information about a function prototype. ExtProtoInfo is not
4523 /// stored as such in FunctionProtoType but is used to group together
4524 /// the various bits of extra information about a function prototype.
4525 struct ExtProtoInfo {
4526 FunctionType::ExtInfo ExtInfo;
4527 unsigned Variadic : 1;
4528 unsigned HasTrailingReturn : 1;
4529 unsigned AArch64SMEAttributes : 8;
4530 Qualifiers TypeQuals;
4531 RefQualifierKind RefQualifier = RQ_None;
4532 ExceptionSpecInfo ExceptionSpec;
4533 const ExtParameterInfo *ExtParameterInfos = nullptr;
4534 SourceLocation EllipsisLoc;
4535
4536 ExtProtoInfo()
4537 : Variadic(false), HasTrailingReturn(false),
4538 AArch64SMEAttributes(SME_NormalFunction) {}
4539
4540 ExtProtoInfo(CallingConv CC)
4541 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false),
4542 AArch64SMEAttributes(SME_NormalFunction) {}
4543
4544 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
4545 ExtProtoInfo Result(*this);
4546 Result.ExceptionSpec = ESI;
4547 return Result;
4548 }
4549
4550 bool requiresFunctionProtoTypeExtraBitfields() const {
4551 return ExceptionSpec.Type == EST_Dynamic ||
4552 requiresFunctionProtoTypeArmAttributes();
4553 }
4554
4555 bool requiresFunctionProtoTypeArmAttributes() const {
4556 return AArch64SMEAttributes != SME_NormalFunction;
4557 }
4558
4559 void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable = true) {
4560 if (Enable)
4561 AArch64SMEAttributes |= Kind;
4562 else
4563 AArch64SMEAttributes &= ~Kind;
4564 }
4565 };
4566
4567private:
4568 unsigned numTrailingObjects(OverloadToken<QualType>) const {
4569 return getNumParams();
4570 }
4571
4572 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
4573 return isVariadic();
4574 }
4575
4576 unsigned numTrailingObjects(OverloadToken<FunctionTypeArmAttributes>) const {
4577 return hasArmTypeAttributes();
4578 }
4579
4580 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
4581 return hasExtraBitfields();
4582 }
4583
4584 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4585 return getExceptionSpecSize().NumExceptionType;
4586 }
4587
4588 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4589 return getExceptionSpecSize().NumExprPtr;
4590 }
4591
4592 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4593 return getExceptionSpecSize().NumFunctionDeclPtr;
4594 }
4595
4596 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4597 return hasExtParameterInfos() ? getNumParams() : 0;
4598 }
4599
4600 /// Determine whether there are any argument types that
4601 /// contain an unexpanded parameter pack.
4602 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4603 unsigned numArgs) {
4604 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4605 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4606 return true;
4607
4608 return false;
4609 }
4610
4611 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4612 QualType canonical, const ExtProtoInfo &epi);
4613
4614 /// This struct is returned by getExceptionSpecSize and is used to
4615 /// translate an ExceptionSpecificationType to the number and kind
4616 /// of trailing objects related to the exception specification.
4617 struct ExceptionSpecSizeHolder {
4618 unsigned NumExceptionType;
4619 unsigned NumExprPtr;
4620 unsigned NumFunctionDeclPtr;
4621 };
4622
4623 /// Return the number and kind of trailing objects
4624 /// related to the exception specification.
4625 static ExceptionSpecSizeHolder
4626 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4627 switch (EST) {
4628 case EST_None:
4629 case EST_DynamicNone:
4630 case EST_MSAny:
4631 case EST_BasicNoexcept:
4632 case EST_Unparsed:
4633 case EST_NoThrow:
4634 return {.NumExceptionType: 0, .NumExprPtr: 0, .NumFunctionDeclPtr: 0};
4635
4636 case EST_Dynamic:
4637 return {.NumExceptionType: NumExceptions, .NumExprPtr: 0, .NumFunctionDeclPtr: 0};
4638
4639 case EST_DependentNoexcept:
4640 case EST_NoexceptFalse:
4641 case EST_NoexceptTrue:
4642 return {.NumExceptionType: 0, .NumExprPtr: 1, .NumFunctionDeclPtr: 0};
4643
4644 case EST_Uninstantiated:
4645 return {.NumExceptionType: 0, .NumExprPtr: 0, .NumFunctionDeclPtr: 2};
4646
4647 case EST_Unevaluated:
4648 return {.NumExceptionType: 0, .NumExprPtr: 0, .NumFunctionDeclPtr: 1};
4649 }
4650 llvm_unreachable("bad exception specification kind");
4651 }
4652
4653 /// Return the number and kind of trailing objects
4654 /// related to the exception specification.
4655 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4656 return getExceptionSpecSize(EST: getExceptionSpecType(), NumExceptions: getNumExceptions());
4657 }
4658
4659 /// Whether the trailing FunctionTypeExtraBitfields is present.
4660 bool hasExtraBitfields() const {
4661 assert((getExceptionSpecType() != EST_Dynamic ||
4662 FunctionTypeBits.HasExtraBitfields) &&
4663 "ExtraBitfields are required for given ExceptionSpecType");
4664 return FunctionTypeBits.HasExtraBitfields;
4665
4666 }
4667
4668 bool hasArmTypeAttributes() const {
4669 return FunctionTypeBits.HasExtraBitfields &&
4670 getTrailingObjects<FunctionTypeExtraBitfields>()
4671 ->HasArmTypeAttributes;
4672 }
4673
4674 bool hasExtQualifiers() const {
4675 return FunctionTypeBits.HasExtQuals;
4676 }
4677
4678public:
4679 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4680
4681 QualType getParamType(unsigned i) const {
4682 assert(i < getNumParams() && "invalid parameter index");
4683 return param_type_begin()[i];
4684 }
4685
4686 ArrayRef<QualType> getParamTypes() const {
4687 return llvm::ArrayRef(param_type_begin(), param_type_end());
4688 }
4689
4690 ExtProtoInfo getExtProtoInfo() const {
4691 ExtProtoInfo EPI;
4692 EPI.ExtInfo = getExtInfo();
4693 EPI.Variadic = isVariadic();
4694 EPI.EllipsisLoc = getEllipsisLoc();
4695 EPI.HasTrailingReturn = hasTrailingReturn();
4696 EPI.ExceptionSpec = getExceptionSpecInfo();
4697 EPI.TypeQuals = getMethodQuals();
4698 EPI.RefQualifier = getRefQualifier();
4699 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4700 EPI.AArch64SMEAttributes = getAArch64SMEAttributes();
4701 return EPI;
4702 }
4703
4704 /// Get the kind of exception specification on this function.
4705 ExceptionSpecificationType getExceptionSpecType() const {
4706 return static_cast<ExceptionSpecificationType>(
4707 FunctionTypeBits.ExceptionSpecType);
4708 }
4709
4710 /// Return whether this function has any kind of exception spec.
4711 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4712
4713 /// Return whether this function has a dynamic (throw) exception spec.
4714 bool hasDynamicExceptionSpec() const {
4715 return isDynamicExceptionSpec(ESpecType: getExceptionSpecType());
4716 }
4717
4718 /// Return whether this function has a noexcept exception spec.
4719 bool hasNoexceptExceptionSpec() const {
4720 return isNoexceptExceptionSpec(ESpecType: getExceptionSpecType());
4721 }
4722
4723 /// Return whether this function has a dependent exception spec.
4724 bool hasDependentExceptionSpec() const;
4725
4726 /// Return whether this function has an instantiation-dependent exception
4727 /// spec.
4728 bool hasInstantiationDependentExceptionSpec() const;
4729
4730 /// Return all the available information about this type's exception spec.
4731 ExceptionSpecInfo getExceptionSpecInfo() const {
4732 ExceptionSpecInfo Result;
4733 Result.Type = getExceptionSpecType();
4734 if (Result.Type == EST_Dynamic) {
4735 Result.Exceptions = exceptions();
4736 } else if (isComputedNoexcept(ESpecType: Result.Type)) {
4737 Result.NoexceptExpr = getNoexceptExpr();
4738 } else if (Result.Type == EST_Uninstantiated) {
4739 Result.SourceDecl = getExceptionSpecDecl();
4740 Result.SourceTemplate = getExceptionSpecTemplate();
4741 } else if (Result.Type == EST_Unevaluated) {
4742 Result.SourceDecl = getExceptionSpecDecl();
4743 }
4744 return Result;
4745 }
4746
4747 /// Return the number of types in the exception specification.
4748 unsigned getNumExceptions() const {
4749 return getExceptionSpecType() == EST_Dynamic
4750 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4751 ->NumExceptionType
4752 : 0;
4753 }
4754
4755 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4756 QualType getExceptionType(unsigned i) const {
4757 assert(i < getNumExceptions() && "Invalid exception number!");
4758 return exception_begin()[i];
4759 }
4760
4761 /// Return the expression inside noexcept(expression), or a null pointer
4762 /// if there is none (because the exception spec is not of this form).
4763 Expr *getNoexceptExpr() const {
4764 if (!isComputedNoexcept(ESpecType: getExceptionSpecType()))
4765 return nullptr;
4766 return *getTrailingObjects<Expr *>();
4767 }
4768
4769 /// If this function type has an exception specification which hasn't
4770 /// been determined yet (either because it has not been evaluated or because
4771 /// it has not been instantiated), this is the function whose exception
4772 /// specification is represented by this type.
4773 FunctionDecl *getExceptionSpecDecl() const {
4774 if (getExceptionSpecType() != EST_Uninstantiated &&
4775 getExceptionSpecType() != EST_Unevaluated)
4776 return nullptr;
4777 return getTrailingObjects<FunctionDecl *>()[0];
4778 }
4779
4780 /// If this function type has an uninstantiated exception
4781 /// specification, this is the function whose exception specification
4782 /// should be instantiated to find the exception specification for
4783 /// this type.
4784 FunctionDecl *getExceptionSpecTemplate() const {
4785 if (getExceptionSpecType() != EST_Uninstantiated)
4786 return nullptr;
4787 return getTrailingObjects<FunctionDecl *>()[1];
4788 }
4789
4790 /// Determine whether this function type has a non-throwing exception
4791 /// specification.
4792 CanThrowResult canThrow() const;
4793
4794 /// Determine whether this function type has a non-throwing exception
4795 /// specification. If this depends on template arguments, returns
4796 /// \c ResultIfDependent.
4797 bool isNothrow(bool ResultIfDependent = false) const {
4798 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4799 }
4800
4801 /// Whether this function prototype is variadic.
4802 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4803
4804 SourceLocation getEllipsisLoc() const {
4805 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4806 : SourceLocation();
4807 }
4808
4809 /// Determines whether this function prototype contains a
4810 /// parameter pack at the end.
4811 ///
4812 /// A function template whose last parameter is a parameter pack can be
4813 /// called with an arbitrary number of arguments, much like a variadic
4814 /// function.
4815 bool isTemplateVariadic() const;
4816
4817 /// Whether this function prototype has a trailing return type.
4818 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4819
4820 Qualifiers getMethodQuals() const {
4821 if (hasExtQualifiers())
4822 return *getTrailingObjects<Qualifiers>();
4823 else
4824 return getFastTypeQuals();
4825 }
4826
4827 /// Retrieve the ref-qualifier associated with this function type.
4828 RefQualifierKind getRefQualifier() const {
4829 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4830 }
4831
4832 using param_type_iterator = const QualType *;
4833
4834 ArrayRef<QualType> param_types() const {
4835 return llvm::ArrayRef(param_type_begin(), param_type_end());
4836 }
4837
4838 param_type_iterator param_type_begin() const {
4839 return getTrailingObjects<QualType>();
4840 }
4841
4842 param_type_iterator param_type_end() const {
4843 return param_type_begin() + getNumParams();
4844 }
4845
4846 using exception_iterator = const QualType *;
4847
4848 ArrayRef<QualType> exceptions() const {
4849 return llvm::ArrayRef(exception_begin(), exception_end());
4850 }
4851
4852 exception_iterator exception_begin() const {
4853 return reinterpret_cast<exception_iterator>(
4854 getTrailingObjects<ExceptionType>());
4855 }
4856
4857 exception_iterator exception_end() const {
4858 return exception_begin() + getNumExceptions();
4859 }
4860
4861 /// Is there any interesting extra information for any of the parameters
4862 /// of this function type?
4863 bool hasExtParameterInfos() const {
4864 return FunctionTypeBits.HasExtParameterInfos;
4865 }
4866
4867 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4868 assert(hasExtParameterInfos());
4869 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4870 getNumParams());
4871 }
4872
4873 /// Return a pointer to the beginning of the array of extra parameter
4874 /// information, if present, or else null if none of the parameters
4875 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4876 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4877 if (!hasExtParameterInfos())
4878 return nullptr;
4879 return getTrailingObjects<ExtParameterInfo>();
4880 }
4881
4882 /// Return a bitmask describing the SME attributes on the function type, see
4883 /// AArch64SMETypeAttributes for their values.
4884 unsigned getAArch64SMEAttributes() const {
4885 if (!hasArmTypeAttributes())
4886 return SME_NormalFunction;
4887 return getTrailingObjects<FunctionTypeArmAttributes>()
4888 ->AArch64SMEAttributes;
4889 }
4890
4891 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4892 assert(I < getNumParams() && "parameter index out of range");
4893 if (hasExtParameterInfos())
4894 return getTrailingObjects<ExtParameterInfo>()[I];
4895 return ExtParameterInfo();
4896 }
4897
4898 ParameterABI getParameterABI(unsigned I) const {
4899 assert(I < getNumParams() && "parameter index out of range");
4900 if (hasExtParameterInfos())
4901 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4902 return ParameterABI::Ordinary;
4903 }
4904
4905 bool isParamConsumed(unsigned I) const {
4906 assert(I < getNumParams() && "parameter index out of range");
4907 if (hasExtParameterInfos())
4908 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4909 return false;
4910 }
4911
4912 bool isSugared() const { return false; }
4913 QualType desugar() const { return QualType(this, 0); }
4914
4915 void printExceptionSpecification(raw_ostream &OS,
4916 const PrintingPolicy &Policy) const;
4917
4918 static bool classof(const Type *T) {
4919 return T->getTypeClass() == FunctionProto;
4920 }
4921
4922 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4923 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4924 param_type_iterator ArgTys, unsigned NumArgs,
4925 const ExtProtoInfo &EPI, const ASTContext &Context,
4926 bool Canonical);
4927};
4928
4929/// Represents the dependent type named by a dependently-scoped
4930/// typename using declaration, e.g.
4931/// using typename Base<T>::foo;
4932///
4933/// Template instantiation turns these into the underlying type.
4934class UnresolvedUsingType : public Type {
4935 friend class ASTContext; // ASTContext creates these.
4936
4937 UnresolvedUsingTypenameDecl *Decl;
4938
4939 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4940 : Type(UnresolvedUsing, QualType(),
4941 TypeDependence::DependentInstantiation),
4942 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4943
4944public:
4945 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4946
4947 bool isSugared() const { return false; }
4948 QualType desugar() const { return QualType(this, 0); }
4949
4950 static bool classof(const Type *T) {
4951 return T->getTypeClass() == UnresolvedUsing;
4952 }
4953
4954 void Profile(llvm::FoldingSetNodeID &ID) {
4955 return Profile(ID, D: Decl);
4956 }
4957
4958 static void Profile(llvm::FoldingSetNodeID &ID,
4959 UnresolvedUsingTypenameDecl *D) {
4960 ID.AddPointer(Ptr: D);
4961 }
4962};
4963
4964class UsingType final : public Type,
4965 public llvm::FoldingSetNode,
4966 private llvm::TrailingObjects<UsingType, QualType> {
4967 UsingShadowDecl *Found;
4968 friend class ASTContext; // ASTContext creates these.
4969 friend TrailingObjects;
4970
4971 UsingType(const UsingShadowDecl *Found, QualType Underlying, QualType Canon);
4972
4973public:
4974 UsingShadowDecl *getFoundDecl() const { return Found; }
4975 QualType getUnderlyingType() const;
4976
4977 bool isSugared() const { return true; }
4978
4979 // This always has the 'same' type as declared, but not necessarily identical.
4980 QualType desugar() const { return getUnderlyingType(); }
4981
4982 // Internal helper, for debugging purposes.
4983 bool typeMatchesDecl() const { return !UsingBits.hasTypeDifferentFromDecl; }
4984
4985 void Profile(llvm::FoldingSetNodeID &ID) {
4986 Profile(ID, Found, Underlying: getUnderlyingType());
4987 }
4988 static void Profile(llvm::FoldingSetNodeID &ID, const UsingShadowDecl *Found,
4989 QualType Underlying) {
4990 ID.AddPointer(Ptr: Found);
4991 Underlying.Profile(ID);
4992 }
4993 static bool classof(const Type *T) { return T->getTypeClass() == Using; }
4994};
4995
4996class TypedefType final : public Type,
4997 public llvm::FoldingSetNode,
4998 private llvm::TrailingObjects<TypedefType, QualType> {
4999 TypedefNameDecl *Decl;
5000 friend class ASTContext; // ASTContext creates these.
5001 friend TrailingObjects;
5002
5003 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
5004 QualType can);
5005
5006public:
5007 TypedefNameDecl *getDecl() const { return Decl; }
5008
5009 bool isSugared() const { return true; }
5010
5011 // This always has the 'same' type as declared, but not necessarily identical.
5012 QualType desugar() const;
5013
5014 // Internal helper, for debugging purposes.
5015 bool typeMatchesDecl() const { return !TypedefBits.hasTypeDifferentFromDecl; }
5016
5017 void Profile(llvm::FoldingSetNodeID &ID) {
5018 Profile(ID, Decl, Underlying: typeMatchesDecl() ? QualType() : desugar());
5019 }
5020 static void Profile(llvm::FoldingSetNodeID &ID, const TypedefNameDecl *Decl,
5021 QualType Underlying) {
5022 ID.AddPointer(Ptr: Decl);
5023 if (!Underlying.isNull())
5024 Underlying.Profile(ID);
5025 }
5026
5027 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
5028};
5029
5030/// Sugar type that represents a type that was qualified by a qualifier written
5031/// as a macro invocation.
5032class MacroQualifiedType : public Type {
5033 friend class ASTContext; // ASTContext creates these.
5034
5035 QualType UnderlyingTy;
5036 const IdentifierInfo *MacroII;
5037
5038 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
5039 const IdentifierInfo *MacroII)
5040 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
5041 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
5042 assert(isa<AttributedType>(UnderlyingTy) &&
5043 "Expected a macro qualified type to only wrap attributed types.");
5044 }
5045
5046public:
5047 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
5048 QualType getUnderlyingType() const { return UnderlyingTy; }
5049
5050 /// Return this attributed type's modified type with no qualifiers attached to
5051 /// it.
5052 QualType getModifiedType() const;
5053
5054 bool isSugared() const { return true; }
5055 QualType desugar() const;
5056
5057 static bool classof(const Type *T) {
5058 return T->getTypeClass() == MacroQualified;
5059 }
5060};
5061
5062/// Represents a `typeof` (or __typeof__) expression (a C23 feature and GCC
5063/// extension) or a `typeof_unqual` expression (a C23 feature).
5064class TypeOfExprType : public Type {
5065 Expr *TOExpr;
5066
5067protected:
5068 friend class ASTContext; // ASTContext creates these.
5069
5070 TypeOfExprType(Expr *E, TypeOfKind Kind, QualType Can = QualType());
5071
5072public:
5073 Expr *getUnderlyingExpr() const { return TOExpr; }
5074
5075 /// Returns the kind of 'typeof' type this is.
5076 TypeOfKind getKind() const {
5077 return TypeOfBits.IsUnqual ? TypeOfKind::Unqualified
5078 : TypeOfKind::Qualified;
5079 }
5080
5081 /// Remove a single level of sugar.
5082 QualType desugar() const;
5083
5084 /// Returns whether this type directly provides sugar.
5085 bool isSugared() const;
5086
5087 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
5088};
5089
5090/// Internal representation of canonical, dependent
5091/// `typeof(expr)` types.
5092///
5093/// This class is used internally by the ASTContext to manage
5094/// canonical, dependent types, only. Clients will only see instances
5095/// of this class via TypeOfExprType nodes.
5096class DependentTypeOfExprType : public TypeOfExprType,
5097 public llvm::FoldingSetNode {
5098public:
5099 DependentTypeOfExprType(Expr *E, TypeOfKind Kind) : TypeOfExprType(E, Kind) {}
5100
5101 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5102 Profile(ID, Context, getUnderlyingExpr(),
5103 getKind() == TypeOfKind::Unqualified);
5104 }
5105
5106 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5107 Expr *E, bool IsUnqual);
5108};
5109
5110/// Represents `typeof(type)`, a C23 feature and GCC extension, or
5111/// `typeof_unqual(type), a C23 feature.
5112class TypeOfType : public Type {
5113 friend class ASTContext; // ASTContext creates these.
5114
5115 QualType TOType;
5116
5117 TypeOfType(QualType T, QualType Can, TypeOfKind Kind)
5118 : Type(TypeOf,
5119 Kind == TypeOfKind::Unqualified ? Can.getAtomicUnqualifiedType()
5120 : Can,
5121 T->getDependence()),
5122 TOType(T) {
5123 TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
5124 }
5125
5126public:
5127 QualType getUnmodifiedType() const { return TOType; }
5128
5129 /// Remove a single level of sugar.
5130 QualType desugar() const {
5131 QualType QT = getUnmodifiedType();
5132 return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
5133 }
5134
5135 /// Returns whether this type directly provides sugar.
5136 bool isSugared() const { return true; }
5137
5138 /// Returns the kind of 'typeof' type this is.
5139 TypeOfKind getKind() const {
5140 return TypeOfBits.IsUnqual ? TypeOfKind::Unqualified
5141 : TypeOfKind::Qualified;
5142 }
5143
5144 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
5145};
5146
5147/// Represents the type `decltype(expr)` (C++11).
5148class DecltypeType : public Type {
5149 Expr *E;
5150 QualType UnderlyingType;
5151
5152protected:
5153 friend class ASTContext; // ASTContext creates these.
5154
5155 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
5156
5157public:
5158 Expr *getUnderlyingExpr() const { return E; }
5159 QualType getUnderlyingType() const { return UnderlyingType; }
5160
5161 /// Remove a single level of sugar.
5162 QualType desugar() const;
5163
5164 /// Returns whether this type directly provides sugar.
5165 bool isSugared() const;
5166
5167 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
5168};
5169
5170/// Internal representation of canonical, dependent
5171/// decltype(expr) types.
5172///
5173/// This class is used internally by the ASTContext to manage
5174/// canonical, dependent types, only. Clients will only see instances
5175/// of this class via DecltypeType nodes.
5176class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
5177public:
5178 DependentDecltypeType(Expr *E, QualType UnderlyingTpe);
5179
5180 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5181 Profile(ID, Context, getUnderlyingExpr());
5182 }
5183
5184 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5185 Expr *E);
5186};
5187
5188class PackIndexingType final
5189 : public Type,
5190 public llvm::FoldingSetNode,
5191 private llvm::TrailingObjects<PackIndexingType, QualType> {
5192 friend TrailingObjects;
5193
5194 const ASTContext &Context;
5195 QualType Pattern;
5196 Expr *IndexExpr;
5197
5198 unsigned Size;
5199
5200protected:
5201 friend class ASTContext; // ASTContext creates these.
5202 PackIndexingType(const ASTContext &Context, QualType Canonical,
5203 QualType Pattern, Expr *IndexExpr,
5204 ArrayRef<QualType> Expansions = {});
5205
5206public:
5207 Expr *getIndexExpr() const { return IndexExpr; }
5208 QualType getPattern() const { return Pattern; }
5209
5210 bool isSugared() const { return hasSelectedType(); }
5211
5212 QualType desugar() const {
5213 if (hasSelectedType())
5214 return getSelectedType();
5215 return QualType(this, 0);
5216 }
5217
5218 QualType getSelectedType() const {
5219 assert(hasSelectedType() && "Type is dependant");
5220 return *(getExpansionsPtr() + *getSelectedIndex());
5221 }
5222
5223 std::optional<unsigned> getSelectedIndex() const;
5224
5225 bool hasSelectedType() const { return getSelectedIndex() != std::nullopt; }
5226
5227 ArrayRef<QualType> getExpansions() const {
5228 return {getExpansionsPtr(), Size};
5229 }
5230
5231 static bool classof(const Type *T) {
5232 return T->getTypeClass() == PackIndexing;
5233 }
5234
5235 void Profile(llvm::FoldingSetNodeID &ID) {
5236 if (hasSelectedType())
5237 getSelectedType().Profile(ID);
5238 else
5239 Profile(ID, Context, Pattern: getPattern(), E: getIndexExpr());
5240 }
5241 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5242 QualType Pattern, Expr *E);
5243
5244private:
5245 const QualType *getExpansionsPtr() const {
5246 return getTrailingObjects<QualType>();
5247 }
5248
5249 static TypeDependence computeDependence(QualType Pattern, Expr *IndexExpr,
5250 ArrayRef<QualType> Expansions = {});
5251
5252 unsigned numTrailingObjects(OverloadToken<QualType>) const { return Size; }
5253};
5254
5255/// A unary type transform, which is a type constructed from another.
5256class UnaryTransformType : public Type {
5257public:
5258 enum UTTKind {
5259#define TRANSFORM_TYPE_TRAIT_DEF(Enum, _) Enum,
5260#include "clang/Basic/TransformTypeTraits.def"
5261 };
5262
5263private:
5264 /// The untransformed type.
5265 QualType BaseType;
5266
5267 /// The transformed type if not dependent, otherwise the same as BaseType.
5268 QualType UnderlyingType;
5269
5270 UTTKind UKind;
5271
5272protected:
5273 friend class ASTContext;
5274
5275 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
5276 QualType CanonicalTy);
5277
5278public:
5279 bool isSugared() const { return !isDependentType(); }
5280 QualType desugar() const { return UnderlyingType; }
5281
5282 QualType getUnderlyingType() const { return UnderlyingType; }
5283 QualType getBaseType() const { return BaseType; }
5284
5285 UTTKind getUTTKind() const { return UKind; }
5286
5287 static bool classof(const Type *T) {
5288 return T->getTypeClass() == UnaryTransform;
5289 }
5290};
5291
5292/// Internal representation of canonical, dependent
5293/// __underlying_type(type) types.
5294///
5295/// This class is used internally by the ASTContext to manage
5296/// canonical, dependent types, only. Clients will only see instances
5297/// of this class via UnaryTransformType nodes.
5298class DependentUnaryTransformType : public UnaryTransformType,
5299 public llvm::FoldingSetNode {
5300public:
5301 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
5302 UTTKind UKind);
5303
5304 void Profile(llvm::FoldingSetNodeID &ID) {
5305 Profile(ID, getBaseType(), getUTTKind());
5306 }
5307
5308 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
5309 UTTKind UKind) {
5310 ID.AddPointer(Ptr: BaseType.getAsOpaquePtr());
5311 ID.AddInteger(I: (unsigned)UKind);
5312 }
5313};
5314
5315class TagType : public Type {
5316 friend class ASTReader;
5317 template <class T> friend class serialization::AbstractTypeReader;
5318
5319 /// Stores the TagDecl associated with this type. The decl may point to any
5320 /// TagDecl that declares the entity.
5321 TagDecl *decl;
5322
5323protected:
5324 TagType(TypeClass TC, const TagDecl *D, QualType can);
5325
5326public:
5327 TagDecl *getDecl() const;
5328
5329 /// Determines whether this type is in the process of being defined.
5330 bool isBeingDefined() const;
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
5334 }
5335};
5336
5337/// A helper class that allows the use of isa/cast/dyncast
5338/// to detect TagType objects of structs/unions/classes.
5339class RecordType : public TagType {
5340protected:
5341 friend class ASTContext; // ASTContext creates these.
5342
5343 explicit RecordType(const RecordDecl *D)
5344 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
5345 explicit RecordType(TypeClass TC, RecordDecl *D)
5346 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
5347
5348public:
5349 RecordDecl *getDecl() const {
5350 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
5351 }
5352
5353 /// Recursively check all fields in the record for const-ness. If any field
5354 /// is declared const, return true. Otherwise, return false.
5355 bool hasConstFields() const;
5356
5357 bool isSugared() const { return false; }
5358 QualType desugar() const { return QualType(this, 0); }
5359
5360 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
5361};
5362
5363/// A helper class that allows the use of isa/cast/dyncast
5364/// to detect TagType objects of enums.
5365class EnumType : public TagType {
5366 friend class ASTContext; // ASTContext creates these.
5367
5368 explicit EnumType(const EnumDecl *D)
5369 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
5370
5371public:
5372 EnumDecl *getDecl() const {
5373 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
5374 }
5375
5376 bool isSugared() const { return false; }
5377 QualType desugar() const { return QualType(this, 0); }
5378
5379 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
5380};
5381
5382/// An attributed type is a type to which a type attribute has been applied.
5383///
5384/// The "modified type" is the fully-sugared type to which the attributed
5385/// type was applied; generally it is not canonically equivalent to the
5386/// attributed type. The "equivalent type" is the minimally-desugared type
5387/// which the type is canonically equivalent to.
5388///
5389/// For example, in the following attributed type:
5390/// int32_t __attribute__((vector_size(16)))
5391/// - the modified type is the TypedefType for int32_t
5392/// - the equivalent type is VectorType(16, int32_t)
5393/// - the canonical type is VectorType(16, int)
5394class AttributedType : public Type, public llvm::FoldingSetNode {
5395public:
5396 using Kind = attr::Kind;
5397
5398private:
5399 friend class ASTContext; // ASTContext creates these
5400
5401 QualType ModifiedType;
5402 QualType EquivalentType;
5403
5404 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
5405 QualType equivalent)
5406 : Type(Attributed, canon, equivalent->getDependence()),
5407 ModifiedType(modified), EquivalentType(equivalent) {
5408 AttributedTypeBits.AttrKind = attrKind;
5409 }
5410
5411public:
5412 Kind getAttrKind() const {
5413 return static_cast<Kind>(AttributedTypeBits.AttrKind);
5414 }
5415
5416 QualType getModifiedType() const { return ModifiedType; }
5417 QualType getEquivalentType() const { return EquivalentType; }
5418
5419 bool isSugared() const { return true; }
5420 QualType desugar() const { return getEquivalentType(); }
5421
5422 /// Does this attribute behave like a type qualifier?
5423 ///
5424 /// A type qualifier adjusts a type to provide specialized rules for
5425 /// a specific object, like the standard const and volatile qualifiers.
5426 /// This includes attributes controlling things like nullability,
5427 /// address spaces, and ARC ownership. The value of the object is still
5428 /// largely described by the modified type.
5429 ///
5430 /// In contrast, many type attributes "rewrite" their modified type to
5431 /// produce a fundamentally different type, not necessarily related in any
5432 /// formalizable way to the original type. For example, calling convention
5433 /// and vector attributes are not simple type qualifiers.
5434 ///
5435 /// Type qualifiers are often, but not always, reflected in the canonical
5436 /// type.
5437 bool isQualifier() const;
5438
5439 bool isMSTypeSpec() const;
5440
5441 bool isWebAssemblyFuncrefSpec() const;
5442
5443 bool isCallingConv() const;
5444
5445 std::optional<NullabilityKind> getImmediateNullability() const;
5446
5447 /// Retrieve the attribute kind corresponding to the given
5448 /// nullability kind.
5449 static Kind getNullabilityAttrKind(NullabilityKind kind) {
5450 switch (kind) {
5451 case NullabilityKind::NonNull:
5452 return attr::TypeNonNull;
5453
5454 case NullabilityKind::Nullable:
5455 return attr::TypeNullable;
5456
5457 case NullabilityKind::NullableResult:
5458 return attr::TypeNullableResult;
5459
5460 case NullabilityKind::Unspecified:
5461 return attr::TypeNullUnspecified;
5462 }
5463 llvm_unreachable("Unknown nullability kind.");
5464 }
5465
5466 /// Strip off the top-level nullability annotation on the given
5467 /// type, if it's there.
5468 ///
5469 /// \param T The type to strip. If the type is exactly an
5470 /// AttributedType specifying nullability (without looking through
5471 /// type sugar), the nullability is returned and this type changed
5472 /// to the underlying modified type.
5473 ///
5474 /// \returns the top-level nullability, if present.
5475 static std::optional<NullabilityKind> stripOuterNullability(QualType &T);
5476
5477 void Profile(llvm::FoldingSetNodeID &ID) {
5478 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
5479 }
5480
5481 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
5482 QualType modified, QualType equivalent) {
5483 ID.AddInteger(I: attrKind);
5484 ID.AddPointer(Ptr: modified.getAsOpaquePtr());
5485 ID.AddPointer(Ptr: equivalent.getAsOpaquePtr());
5486 }
5487
5488 static bool classof(const Type *T) {
5489 return T->getTypeClass() == Attributed;
5490 }
5491};
5492
5493class BTFTagAttributedType : public Type, public llvm::FoldingSetNode {
5494private:
5495 friend class ASTContext; // ASTContext creates these
5496
5497 QualType WrappedType;
5498 const BTFTypeTagAttr *BTFAttr;
5499
5500 BTFTagAttributedType(QualType Canon, QualType Wrapped,
5501 const BTFTypeTagAttr *BTFAttr)
5502 : Type(BTFTagAttributed, Canon, Wrapped->getDependence()),
5503 WrappedType(Wrapped), BTFAttr(BTFAttr) {}
5504
5505public:
5506 QualType getWrappedType() const { return WrappedType; }
5507 const BTFTypeTagAttr *getAttr() const { return BTFAttr; }
5508
5509 bool isSugared() const { return true; }
5510 QualType desugar() const { return getWrappedType(); }
5511
5512 void Profile(llvm::FoldingSetNodeID &ID) {
5513 Profile(ID, WrappedType, BTFAttr);
5514 }
5515
5516 static void Profile(llvm::FoldingSetNodeID &ID, QualType Wrapped,
5517 const BTFTypeTagAttr *BTFAttr) {
5518 ID.AddPointer(Ptr: Wrapped.getAsOpaquePtr());
5519 ID.AddPointer(Ptr: BTFAttr);
5520 }
5521
5522 static bool classof(const Type *T) {
5523 return T->getTypeClass() == BTFTagAttributed;
5524 }
5525};
5526
5527class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
5528 friend class ASTContext; // ASTContext creates these
5529
5530 // Helper data collector for canonical types.
5531 struct CanonicalTTPTInfo {
5532 unsigned Depth : 15;
5533 unsigned ParameterPack : 1;
5534 unsigned Index : 16;
5535 };
5536
5537 union {
5538 // Info for the canonical type.
5539 CanonicalTTPTInfo CanTTPTInfo;
5540
5541 // Info for the non-canonical type.
5542 TemplateTypeParmDecl *TTPDecl;
5543 };
5544
5545 /// Build a non-canonical type.
5546 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
5547 : Type(TemplateTypeParm, Canon,
5548 TypeDependence::DependentInstantiation |
5549 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
5550 TTPDecl(TTPDecl) {}
5551
5552 /// Build the canonical type.
5553 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
5554 : Type(TemplateTypeParm, QualType(this, 0),
5555 TypeDependence::DependentInstantiation |
5556 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
5557 CanTTPTInfo.Depth = D;
5558 CanTTPTInfo.Index = I;
5559 CanTTPTInfo.ParameterPack = PP;
5560 }
5561
5562 const CanonicalTTPTInfo& getCanTTPTInfo() const {
5563 QualType Can = getCanonicalTypeInternal();
5564 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
5565 }
5566
5567public:
5568 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
5569 unsigned getIndex() const { return getCanTTPTInfo().Index; }
5570 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
5571
5572 TemplateTypeParmDecl *getDecl() const {
5573 return isCanonicalUnqualified() ? nullptr : TTPDecl;
5574 }
5575
5576 IdentifierInfo *getIdentifier() const;
5577
5578 bool isSugared() const { return false; }
5579 QualType desugar() const { return QualType(this, 0); }
5580
5581 void Profile(llvm::FoldingSetNodeID &ID) {
5582 Profile(ID, Depth: getDepth(), Index: getIndex(), ParameterPack: isParameterPack(), TTPDecl: getDecl());
5583 }
5584
5585 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
5586 unsigned Index, bool ParameterPack,
5587 TemplateTypeParmDecl *TTPDecl) {
5588 ID.AddInteger(I: Depth);
5589 ID.AddInteger(I: Index);
5590 ID.AddBoolean(B: ParameterPack);
5591 ID.AddPointer(Ptr: TTPDecl);
5592 }
5593
5594 static bool classof(const Type *T) {
5595 return T->getTypeClass() == TemplateTypeParm;
5596 }
5597};
5598
5599/// Represents the result of substituting a type for a template
5600/// type parameter.
5601///
5602/// Within an instantiated template, all template type parameters have
5603/// been replaced with these. They are used solely to record that a
5604/// type was originally written as a template type parameter;
5605/// therefore they are never canonical.
5606class SubstTemplateTypeParmType final
5607 : public Type,
5608 public llvm::FoldingSetNode,
5609 private llvm::TrailingObjects<SubstTemplateTypeParmType, QualType> {
5610 friend class ASTContext;
5611 friend class llvm::TrailingObjects<SubstTemplateTypeParmType, QualType>;
5612
5613 Decl *AssociatedDecl;
5614
5615 SubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
5616 unsigned Index, std::optional<unsigned> PackIndex);
5617
5618public:
5619 /// Gets the type that was substituted for the template
5620 /// parameter.
5621 QualType getReplacementType() const {
5622 return SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType
5623 ? *getTrailingObjects<QualType>()
5624 : getCanonicalTypeInternal();
5625 }
5626
5627 /// A template-like entity which owns the whole pattern being substituted.
5628 /// This will usually own a set of template parameters, or in some
5629 /// cases might even be a template parameter itself.
5630 Decl *getAssociatedDecl() const { return AssociatedDecl; }
5631
5632 /// Gets the template parameter declaration that was substituted for.
5633 const TemplateTypeParmDecl *getReplacedParameter() const;
5634
5635 /// Returns the index of the replaced parameter in the associated declaration.
5636 /// This should match the result of `getReplacedParameter()->getIndex()`.
5637 unsigned getIndex() const { return SubstTemplateTypeParmTypeBits.Index; }
5638
5639 std::optional<unsigned> getPackIndex() const {
5640 if (SubstTemplateTypeParmTypeBits.PackIndex == 0)
5641 return std::nullopt;
5642 return SubstTemplateTypeParmTypeBits.PackIndex - 1;
5643 }
5644
5645 bool isSugared() const { return true; }
5646 QualType desugar() const { return getReplacementType(); }
5647
5648 void Profile(llvm::FoldingSetNodeID &ID) {
5649 Profile(ID, Replacement: getReplacementType(), AssociatedDecl: getAssociatedDecl(), Index: getIndex(),
5650 PackIndex: getPackIndex());
5651 }
5652
5653 static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement,
5654 const Decl *AssociatedDecl, unsigned Index,
5655 std::optional<unsigned> PackIndex) {
5656 Replacement.Profile(ID);
5657 ID.AddPointer(Ptr: AssociatedDecl);
5658 ID.AddInteger(I: Index);
5659 ID.AddInteger(I: PackIndex ? *PackIndex - 1 : 0);
5660 }
5661
5662 static bool classof(const Type *T) {
5663 return T->getTypeClass() == SubstTemplateTypeParm;
5664 }
5665};
5666
5667/// Represents the result of substituting a set of types for a template
5668/// type parameter pack.
5669///
5670/// When a pack expansion in the source code contains multiple parameter packs
5671/// and those parameter packs correspond to different levels of template
5672/// parameter lists, this type node is used to represent a template type
5673/// parameter pack from an outer level, which has already had its argument pack
5674/// substituted but that still lives within a pack expansion that itself
5675/// could not be instantiated. When actually performing a substitution into
5676/// that pack expansion (e.g., when all template parameters have corresponding
5677/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
5678/// at the current pack substitution index.
5679class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
5680 friend class ASTContext;
5681
5682 /// A pointer to the set of template arguments that this
5683 /// parameter pack is instantiated with.
5684 const TemplateArgument *Arguments;
5685
5686 llvm::PointerIntPair<Decl *, 1, bool> AssociatedDeclAndFinal;
5687
5688 SubstTemplateTypeParmPackType(QualType Canon, Decl *AssociatedDecl,
5689 unsigned Index, bool Final,
5690 const TemplateArgument &ArgPack);
5691
5692public:
5693 IdentifierInfo *getIdentifier() const;
5694
5695 /// A template-like entity which owns the whole pattern being substituted.
5696 /// This will usually own a set of template parameters, or in some
5697 /// cases might even be a template parameter itself.
5698 Decl *getAssociatedDecl() const;
5699
5700 /// Gets the template parameter declaration that was substituted for.
5701 const TemplateTypeParmDecl *getReplacedParameter() const;
5702
5703 /// Returns the index of the replaced parameter in the associated declaration.
5704 /// This should match the result of `getReplacedParameter()->getIndex()`.
5705 unsigned getIndex() const { return SubstTemplateTypeParmPackTypeBits.Index; }
5706
5707 // When true the substitution will be 'Final' (subst node won't be placed).
5708 bool getFinal() const;
5709
5710 unsigned getNumArgs() const {
5711 return SubstTemplateTypeParmPackTypeBits.NumArgs;
5712 }
5713
5714 bool isSugared() const { return false; }
5715 QualType desugar() const { return QualType(this, 0); }
5716
5717 TemplateArgument getArgumentPack() const;
5718
5719 void Profile(llvm::FoldingSetNodeID &ID);
5720 static void Profile(llvm::FoldingSetNodeID &ID, const Decl *AssociatedDecl,
5721 unsigned Index, bool Final,
5722 const TemplateArgument &ArgPack);
5723
5724 static bool classof(const Type *T) {
5725 return T->getTypeClass() == SubstTemplateTypeParmPack;
5726 }
5727};
5728
5729/// Common base class for placeholders for types that get replaced by
5730/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
5731/// class template types, and constrained type names.
5732///
5733/// These types are usually a placeholder for a deduced type. However, before
5734/// the initializer is attached, or (usually) if the initializer is
5735/// type-dependent, there is no deduced type and the type is canonical. In
5736/// the latter case, it is also a dependent type.
5737class DeducedType : public Type {
5738 QualType DeducedAsType;
5739
5740protected:
5741 DeducedType(TypeClass TC, QualType DeducedAsType,
5742 TypeDependence ExtraDependence, QualType Canon)
5743 : Type(TC, Canon,
5744 ExtraDependence | (DeducedAsType.isNull()
5745 ? TypeDependence::None
5746 : DeducedAsType->getDependence() &
5747 ~TypeDependence::VariablyModified)),
5748 DeducedAsType(DeducedAsType) {}
5749
5750public:
5751 bool isSugared() const { return !DeducedAsType.isNull(); }
5752 QualType desugar() const {
5753 return isSugared() ? DeducedAsType : QualType(this, 0);
5754 }
5755
5756 /// Get the type deduced for this placeholder type, or null if it
5757 /// has not been deduced.
5758 QualType getDeducedType() const { return DeducedAsType; }
5759 bool isDeduced() const {
5760 return !DeducedAsType.isNull() || isDependentType();
5761 }
5762
5763 static bool classof(const Type *T) {
5764 return T->getTypeClass() == Auto ||
5765 T->getTypeClass() == DeducedTemplateSpecialization;
5766 }
5767};
5768
5769/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
5770/// by a type-constraint.
5771class AutoType : public DeducedType, public llvm::FoldingSetNode {
5772 friend class ASTContext; // ASTContext creates these
5773
5774 ConceptDecl *TypeConstraintConcept;
5775
5776 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
5777 TypeDependence ExtraDependence, QualType Canon, ConceptDecl *CD,
5778 ArrayRef<TemplateArgument> TypeConstraintArgs);
5779
5780public:
5781 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5782 return {reinterpret_cast<const TemplateArgument *>(this + 1),
5783 AutoTypeBits.NumArgs};
5784 }
5785
5786 ConceptDecl *getTypeConstraintConcept() const {
5787 return TypeConstraintConcept;
5788 }
5789
5790 bool isConstrained() const {
5791 return TypeConstraintConcept != nullptr;
5792 }
5793
5794 bool isDecltypeAuto() const {
5795 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5796 }
5797
5798 bool isGNUAutoType() const {
5799 return getKeyword() == AutoTypeKeyword::GNUAutoType;
5800 }
5801
5802 AutoTypeKeyword getKeyword() const {
5803 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5804 }
5805
5806 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context);
5807 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5808 QualType Deduced, AutoTypeKeyword Keyword,
5809 bool IsDependent, ConceptDecl *CD,
5810 ArrayRef<TemplateArgument> Arguments);
5811
5812 static bool classof(const Type *T) {
5813 return T->getTypeClass() == Auto;
5814 }
5815};
5816
5817/// Represents a C++17 deduced template specialization type.
5818class DeducedTemplateSpecializationType : public DeducedType,
5819 public llvm::FoldingSetNode {
5820 friend class ASTContext; // ASTContext creates these
5821
5822 /// The name of the template whose arguments will be deduced.
5823 TemplateName Template;
5824
5825 DeducedTemplateSpecializationType(TemplateName Template,
5826 QualType DeducedAsType,
5827 bool IsDeducedAsDependent)
5828 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5829 toTypeDependence(Template.getDependence()) |
5830 (IsDeducedAsDependent
5831 ? TypeDependence::DependentInstantiation
5832 : TypeDependence::None),
5833 DeducedAsType.isNull() ? QualType(this, 0)
5834 : DeducedAsType.getCanonicalType()),
5835 Template(Template) {}
5836
5837public:
5838 /// Retrieve the name of the template that we are deducing.
5839 TemplateName getTemplateName() const { return Template;}
5840
5841 void Profile(llvm::FoldingSetNodeID &ID) {
5842 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5843 }
5844
5845 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5846 QualType Deduced, bool IsDependent) {
5847 Template.Profile(ID);
5848 QualType CanonicalType =
5849 Deduced.isNull() ? Deduced : Deduced.getCanonicalType();
5850 ID.AddPointer(Ptr: CanonicalType.getAsOpaquePtr());
5851 ID.AddBoolean(B: IsDependent || Template.isDependent());
5852 }
5853
5854 static bool classof(const Type *T) {
5855 return T->getTypeClass() == DeducedTemplateSpecialization;
5856 }
5857};
5858
5859/// Represents a type template specialization; the template
5860/// must be a class template, a type alias template, or a template
5861/// template parameter. A template which cannot be resolved to one of
5862/// these, e.g. because it is written with a dependent scope
5863/// specifier, is instead represented as a
5864/// @c DependentTemplateSpecializationType.
5865///
5866/// A non-dependent template specialization type is always "sugar",
5867/// typically for a \c RecordType. For example, a class template
5868/// specialization type of \c vector<int> will refer to a tag type for
5869/// the instantiation \c std::vector<int, std::allocator<int>>
5870///
5871/// Template specializations are dependent if either the template or
5872/// any of the template arguments are dependent, in which case the
5873/// type may also be canonical.
5874///
5875/// Instances of this type are allocated with a trailing array of
5876/// TemplateArguments, followed by a QualType representing the
5877/// non-canonical aliased type when the template is a type alias
5878/// template.
5879class TemplateSpecializationType : public Type, public llvm::FoldingSetNode {
5880 friend class ASTContext; // ASTContext creates these
5881
5882 /// The name of the template being specialized. This is
5883 /// either a TemplateName::Template (in which case it is a
5884 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5885 /// TypeAliasTemplateDecl*), a
5886 /// TemplateName::SubstTemplateTemplateParmPack, or a
5887 /// TemplateName::SubstTemplateTemplateParm (in which case the
5888 /// replacement must, recursively, be one of these).
5889 TemplateName Template;
5890
5891 TemplateSpecializationType(TemplateName T,
5892 ArrayRef<TemplateArgument> Args,
5893 QualType Canon,
5894 QualType Aliased);
5895
5896public:
5897 /// Determine whether any of the given template arguments are dependent.
5898 ///
5899 /// The converted arguments should be supplied when known; whether an
5900 /// argument is dependent can depend on the conversions performed on it
5901 /// (for example, a 'const int' passed as a template argument might be
5902 /// dependent if the parameter is a reference but non-dependent if the
5903 /// parameter is an int).
5904 ///
5905 /// Note that the \p Args parameter is unused: this is intentional, to remind
5906 /// the caller that they need to pass in the converted arguments, not the
5907 /// specified arguments.
5908 static bool
5909 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5910 ArrayRef<TemplateArgument> Converted);
5911 static bool
5912 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5913 ArrayRef<TemplateArgument> Converted);
5914 static bool anyInstantiationDependentTemplateArguments(
5915 ArrayRef<TemplateArgumentLoc> Args);
5916
5917 /// True if this template specialization type matches a current
5918 /// instantiation in the context in which it is found.
5919 bool isCurrentInstantiation() const {
5920 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5921 }
5922
5923 /// Determine if this template specialization type is for a type alias
5924 /// template that has been substituted.
5925 ///
5926 /// Nearly every template specialization type whose template is an alias
5927 /// template will be substituted. However, this is not the case when
5928 /// the specialization contains a pack expansion but the template alias
5929 /// does not have a corresponding parameter pack, e.g.,
5930 ///
5931 /// \code
5932 /// template<typename T, typename U, typename V> struct S;
5933 /// template<typename T, typename U> using A = S<T, int, U>;
5934 /// template<typename... Ts> struct X {
5935 /// typedef A<Ts...> type; // not a type alias
5936 /// };
5937 /// \endcode
5938 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5939
5940 /// Get the aliased type, if this is a specialization of a type alias
5941 /// template.
5942 QualType getAliasedType() const;
5943
5944 /// Retrieve the name of the template that we are specializing.
5945 TemplateName getTemplateName() const { return Template; }
5946
5947 ArrayRef<TemplateArgument> template_arguments() const {
5948 return {reinterpret_cast<const TemplateArgument *>(this + 1),
5949 TemplateSpecializationTypeBits.NumArgs};
5950 }
5951
5952 bool isSugared() const {
5953 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5954 }
5955
5956 QualType desugar() const {
5957 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5958 }
5959
5960 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
5961 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5962 ArrayRef<TemplateArgument> Args,
5963 const ASTContext &Context);
5964
5965 static bool classof(const Type *T) {
5966 return T->getTypeClass() == TemplateSpecialization;
5967 }
5968};
5969
5970/// Print a template argument list, including the '<' and '>'
5971/// enclosing the template arguments.
5972void printTemplateArgumentList(raw_ostream &OS,
5973 ArrayRef<TemplateArgument> Args,
5974 const PrintingPolicy &Policy,
5975 const TemplateParameterList *TPL = nullptr);
5976
5977void printTemplateArgumentList(raw_ostream &OS,
5978 ArrayRef<TemplateArgumentLoc> Args,
5979 const PrintingPolicy &Policy,
5980 const TemplateParameterList *TPL = nullptr);
5981
5982void printTemplateArgumentList(raw_ostream &OS,
5983 const TemplateArgumentListInfo &Args,
5984 const PrintingPolicy &Policy,
5985 const TemplateParameterList *TPL = nullptr);
5986
5987/// Make a best-effort determination of whether the type T can be produced by
5988/// substituting Args into the default argument of Param.
5989bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg,
5990 const NamedDecl *Param,
5991 ArrayRef<TemplateArgument> Args,
5992 unsigned Depth);
5993
5994/// The injected class name of a C++ class template or class
5995/// template partial specialization. Used to record that a type was
5996/// spelled with a bare identifier rather than as a template-id; the
5997/// equivalent for non-templated classes is just RecordType.
5998///
5999/// Injected class name types are always dependent. Template
6000/// instantiation turns these into RecordTypes.
6001///
6002/// Injected class name types are always canonical. This works
6003/// because it is impossible to compare an injected class name type
6004/// with the corresponding non-injected template type, for the same
6005/// reason that it is impossible to directly compare template
6006/// parameters from different dependent contexts: injected class name
6007/// types can only occur within the scope of a particular templated
6008/// declaration, and within that scope every template specialization
6009/// will canonicalize to the injected class name (when appropriate
6010/// according to the rules of the language).
6011class InjectedClassNameType : public Type {
6012 friend class ASTContext; // ASTContext creates these.
6013 friend class ASTNodeImporter;
6014 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
6015 // currently suitable for AST reading, too much
6016 // interdependencies.
6017 template <class T> friend class serialization::AbstractTypeReader;
6018
6019 CXXRecordDecl *Decl;
6020
6021 /// The template specialization which this type represents.
6022 /// For example, in
6023 /// template <class T> class A { ... };
6024 /// this is A<T>, whereas in
6025 /// template <class X, class Y> class A<B<X,Y> > { ... };
6026 /// this is A<B<X,Y> >.
6027 ///
6028 /// It is always unqualified, always a template specialization type,
6029 /// and always dependent.
6030 QualType InjectedType;
6031
6032 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
6033 : Type(InjectedClassName, QualType(),
6034 TypeDependence::DependentInstantiation),
6035 Decl(D), InjectedType(TST) {
6036 assert(isa<TemplateSpecializationType>(TST));
6037 assert(!TST.hasQualifiers());
6038 assert(TST->isDependentType());
6039 }
6040
6041public:
6042 QualType getInjectedSpecializationType() const { return InjectedType; }
6043
6044 const TemplateSpecializationType *getInjectedTST() const {
6045 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
6046 }
6047
6048 TemplateName getTemplateName() const {
6049 return getInjectedTST()->getTemplateName();
6050 }
6051
6052 CXXRecordDecl *getDecl() const;
6053
6054 bool isSugared() const { return false; }
6055 QualType desugar() const { return QualType(this, 0); }
6056
6057 static bool classof(const Type *T) {
6058 return T->getTypeClass() == InjectedClassName;
6059 }
6060};
6061
6062/// The elaboration keyword that precedes a qualified type name or
6063/// introduces an elaborated-type-specifier.
6064enum class ElaboratedTypeKeyword {
6065 /// The "struct" keyword introduces the elaborated-type-specifier.
6066 Struct,
6067
6068 /// The "__interface" keyword introduces the elaborated-type-specifier.
6069 Interface,
6070
6071 /// The "union" keyword introduces the elaborated-type-specifier.
6072 Union,
6073
6074 /// The "class" keyword introduces the elaborated-type-specifier.
6075 Class,
6076
6077 /// The "enum" keyword introduces the elaborated-type-specifier.
6078 Enum,
6079
6080 /// The "typename" keyword precedes the qualified type name, e.g.,
6081 /// \c typename T::type.
6082 Typename,
6083
6084 /// No keyword precedes the qualified type name.
6085 None
6086};
6087
6088/// The kind of a tag type.
6089enum class TagTypeKind {
6090 /// The "struct" keyword.
6091 Struct,
6092
6093 /// The "__interface" keyword.
6094 Interface,
6095
6096 /// The "union" keyword.
6097 Union,
6098
6099 /// The "class" keyword.
6100 Class,
6101
6102 /// The "enum" keyword.
6103 Enum
6104};
6105
6106/// A helper class for Type nodes having an ElaboratedTypeKeyword.
6107/// The keyword in stored in the free bits of the base class.
6108/// Also provides a few static helpers for converting and printing
6109/// elaborated type keyword and tag type kind enumerations.
6110class TypeWithKeyword : public Type {
6111protected:
6112 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
6113 QualType Canonical, TypeDependence Dependence)
6114 : Type(tc, Canonical, Dependence) {
6115 TypeWithKeywordBits.Keyword = llvm::to_underlying(Keyword);
6116 }
6117
6118public:
6119 ElaboratedTypeKeyword getKeyword() const {
6120 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
6121 }
6122
6123 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
6124 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
6125
6126 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
6127 /// It is an error to provide a type specifier which *isn't* a tag kind here.
6128 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
6129
6130 /// Converts a TagTypeKind into an elaborated type keyword.
6131 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
6132
6133 /// Converts an elaborated type keyword into a TagTypeKind.
6134 /// It is an error to provide an elaborated type keyword
6135 /// which *isn't* a tag kind here.
6136 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
6137
6138 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
6139
6140 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
6141
6142 static StringRef getTagTypeKindName(TagTypeKind Kind) {
6143 return getKeywordName(Keyword: getKeywordForTagTypeKind(Tag: Kind));
6144 }
6145
6146 class CannotCastToThisType {};
6147 static CannotCastToThisType classof(const Type *);
6148};
6149
6150/// Represents a type that was referred to using an elaborated type
6151/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
6152/// or both.
6153///
6154/// This type is used to keep track of a type name as written in the
6155/// source code, including tag keywords and any nested-name-specifiers.
6156/// The type itself is always "sugar", used to express what was written
6157/// in the source code but containing no additional semantic information.
6158class ElaboratedType final
6159 : public TypeWithKeyword,
6160 public llvm::FoldingSetNode,
6161 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
6162 friend class ASTContext; // ASTContext creates these
6163 friend TrailingObjects;
6164
6165 /// The nested name specifier containing the qualifier.
6166 NestedNameSpecifier *NNS;
6167
6168 /// The type that this qualified name refers to.
6169 QualType NamedType;
6170
6171 /// The (re)declaration of this tag type owned by this occurrence is stored
6172 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
6173 /// it, or obtain a null pointer if there is none.
6174
6175 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
6176 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
6177 : TypeWithKeyword(Keyword, Elaborated, CanonType,
6178 // Any semantic dependence on the qualifier will have
6179 // been incorporated into NamedType. We still need to
6180 // track syntactic (instantiation / error / pack)
6181 // dependence on the qualifier.
6182 NamedType->getDependence() |
6183 (NNS ? toSyntacticDependence(
6184 toTypeDependence(NNS->getDependence()))
6185 : TypeDependence::None)),
6186 NNS(NNS), NamedType(NamedType) {
6187 ElaboratedTypeBits.HasOwnedTagDecl = false;
6188 if (OwnedTagDecl) {
6189 ElaboratedTypeBits.HasOwnedTagDecl = true;
6190 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
6191 }
6192 }
6193
6194public:
6195 /// Retrieve the qualification on this type.
6196 NestedNameSpecifier *getQualifier() const { return NNS; }
6197
6198 /// Retrieve the type named by the qualified-id.
6199 QualType getNamedType() const { return NamedType; }
6200
6201 /// Remove a single level of sugar.
6202 QualType desugar() const { return getNamedType(); }
6203
6204 /// Returns whether this type directly provides sugar.
6205 bool isSugared() const { return true; }
6206
6207 /// Return the (re)declaration of this type owned by this occurrence of this
6208 /// type, or nullptr if there is none.
6209 TagDecl *getOwnedTagDecl() const {
6210 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
6211 : nullptr;
6212 }
6213
6214 void Profile(llvm::FoldingSetNodeID &ID) {
6215 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
6216 }
6217
6218 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
6219 NestedNameSpecifier *NNS, QualType NamedType,
6220 TagDecl *OwnedTagDecl) {
6221 ID.AddInteger(llvm::to_underlying(Keyword));
6222 ID.AddPointer(Ptr: NNS);
6223 NamedType.Profile(ID);
6224 ID.AddPointer(Ptr: OwnedTagDecl);
6225 }
6226
6227 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
6228};
6229
6230/// Represents a qualified type name for which the type name is
6231/// dependent.
6232///
6233/// DependentNameType represents a class of dependent types that involve a
6234/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
6235/// name of a type. The DependentNameType may start with a "typename" (for a
6236/// typename-specifier), "class", "struct", "union", or "enum" (for a
6237/// dependent elaborated-type-specifier), or nothing (in contexts where we
6238/// know that we must be referring to a type, e.g., in a base class specifier).
6239/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
6240/// mode, this type is used with non-dependent names to delay name lookup until
6241/// instantiation.
6242class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
6243 friend class ASTContext; // ASTContext creates these
6244
6245 /// The nested name specifier containing the qualifier.
6246 NestedNameSpecifier *NNS;
6247
6248 /// The type that this typename specifier refers to.
6249 const IdentifierInfo *Name;
6250
6251 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
6252 const IdentifierInfo *Name, QualType CanonType)
6253 : TypeWithKeyword(Keyword, DependentName, CanonType,
6254 TypeDependence::DependentInstantiation |
6255 toTypeDependence(NNS->getDependence())),
6256 NNS(NNS), Name(Name) {}
6257
6258public:
6259 /// Retrieve the qualification on this type.
6260 NestedNameSpecifier *getQualifier() const { return NNS; }
6261
6262 /// Retrieve the type named by the typename specifier as an identifier.
6263 ///
6264 /// This routine will return a non-NULL identifier pointer when the
6265 /// form of the original typename was terminated by an identifier,
6266 /// e.g., "typename T::type".
6267 const IdentifierInfo *getIdentifier() const {
6268 return Name;
6269 }
6270
6271 bool isSugared() const { return false; }
6272 QualType desugar() const { return QualType(this, 0); }
6273
6274 void Profile(llvm::FoldingSetNodeID &ID) {
6275 Profile(ID, getKeyword(), NNS, Name);
6276 }
6277
6278 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
6279 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
6280 ID.AddInteger(llvm::to_underlying(Keyword));
6281 ID.AddPointer(Ptr: NNS);
6282 ID.AddPointer(Ptr: Name);
6283 }
6284
6285 static bool classof(const Type *T) {
6286 return T->getTypeClass() == DependentName;
6287 }
6288};
6289
6290/// Represents a template specialization type whose template cannot be
6291/// resolved, e.g.
6292/// A<T>::template B<T>
6293class DependentTemplateSpecializationType : public TypeWithKeyword,
6294 public llvm::FoldingSetNode {
6295 friend class ASTContext; // ASTContext creates these
6296
6297 /// The nested name specifier containing the qualifier.
6298 NestedNameSpecifier *NNS;
6299
6300 /// The identifier of the template.
6301 const IdentifierInfo *Name;
6302
6303 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
6304 NestedNameSpecifier *NNS,
6305 const IdentifierInfo *Name,
6306 ArrayRef<TemplateArgument> Args,
6307 QualType Canon);
6308
6309public:
6310 NestedNameSpecifier *getQualifier() const { return NNS; }
6311 const IdentifierInfo *getIdentifier() const { return Name; }
6312
6313 ArrayRef<TemplateArgument> template_arguments() const {
6314 return {reinterpret_cast<const TemplateArgument *>(this + 1),
6315 DependentTemplateSpecializationTypeBits.NumArgs};
6316 }
6317
6318 bool isSugared() const { return false; }
6319 QualType desugar() const { return QualType(this, 0); }
6320
6321 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
6322 Profile(ID, Context, getKeyword(), NNS, Name, template_arguments());
6323 }
6324
6325 static void Profile(llvm::FoldingSetNodeID &ID,
6326 const ASTContext &Context,
6327 ElaboratedTypeKeyword Keyword,
6328 NestedNameSpecifier *Qualifier,
6329 const IdentifierInfo *Name,
6330 ArrayRef<TemplateArgument> Args);
6331
6332 static bool classof(const Type *T) {
6333 return T->getTypeClass() == DependentTemplateSpecialization;
6334 }
6335};
6336
6337/// Represents a pack expansion of types.
6338///
6339/// Pack expansions are part of C++11 variadic templates. A pack
6340/// expansion contains a pattern, which itself contains one or more
6341/// "unexpanded" parameter packs. When instantiated, a pack expansion
6342/// produces a series of types, each instantiated from the pattern of
6343/// the expansion, where the Ith instantiation of the pattern uses the
6344/// Ith arguments bound to each of the unexpanded parameter packs. The
6345/// pack expansion is considered to "expand" these unexpanded
6346/// parameter packs.
6347///
6348/// \code
6349/// template<typename ...Types> struct tuple;
6350///
6351/// template<typename ...Types>
6352/// struct tuple_of_references {
6353/// typedef tuple<Types&...> type;
6354/// };
6355/// \endcode
6356///
6357/// Here, the pack expansion \c Types&... is represented via a
6358/// PackExpansionType whose pattern is Types&.
6359class PackExpansionType : public Type, public llvm::FoldingSetNode {
6360 friend class ASTContext; // ASTContext creates these
6361
6362 /// The pattern of the pack expansion.
6363 QualType Pattern;
6364
6365 PackExpansionType(QualType Pattern, QualType Canon,
6366 std::optional<unsigned> NumExpansions)
6367 : Type(PackExpansion, Canon,
6368 (Pattern->getDependence() | TypeDependence::Dependent |
6369 TypeDependence::Instantiation) &
6370 ~TypeDependence::UnexpandedPack),
6371 Pattern(Pattern) {
6372 PackExpansionTypeBits.NumExpansions =
6373 NumExpansions ? *NumExpansions + 1 : 0;
6374 }
6375
6376public:
6377 /// Retrieve the pattern of this pack expansion, which is the
6378 /// type that will be repeatedly instantiated when instantiating the
6379 /// pack expansion itself.
6380 QualType getPattern() const { return Pattern; }
6381
6382 /// Retrieve the number of expansions that this pack expansion will
6383 /// generate, if known.
6384 std::optional<unsigned> getNumExpansions() const {
6385 if (PackExpansionTypeBits.NumExpansions)
6386 return PackExpansionTypeBits.NumExpansions - 1;
6387 return std::nullopt;
6388 }
6389
6390 bool isSugared() const { return false; }
6391 QualType desugar() const { return QualType(this, 0); }
6392
6393 void Profile(llvm::FoldingSetNodeID &ID) {
6394 Profile(ID, Pattern: getPattern(), NumExpansions: getNumExpansions());
6395 }
6396
6397 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
6398 std::optional<unsigned> NumExpansions) {
6399 ID.AddPointer(Ptr: Pattern.getAsOpaquePtr());
6400 ID.AddBoolean(B: NumExpansions.has_value());
6401 if (NumExpansions)
6402 ID.AddInteger(I: *NumExpansions);
6403 }
6404
6405 static bool classof(const Type *T) {
6406 return T->getTypeClass() == PackExpansion;
6407 }
6408};
6409
6410/// This class wraps the list of protocol qualifiers. For types that can
6411/// take ObjC protocol qualifers, they can subclass this class.
6412template <class T>
6413class ObjCProtocolQualifiers {
6414protected:
6415 ObjCProtocolQualifiers() = default;
6416
6417 ObjCProtocolDecl * const *getProtocolStorage() const {
6418 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
6419 }
6420
6421 ObjCProtocolDecl **getProtocolStorage() {
6422 return static_cast<T*>(this)->getProtocolStorageImpl();
6423 }
6424
6425 void setNumProtocols(unsigned N) {
6426 static_cast<T*>(this)->setNumProtocolsImpl(N);
6427 }
6428
6429 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
6430 setNumProtocols(protocols.size());
6431 assert(getNumProtocols() == protocols.size() &&
6432 "bitfield overflow in protocol count");
6433 if (!protocols.empty())
6434 memcpy(getProtocolStorage(), protocols.data(),
6435 protocols.size() * sizeof(ObjCProtocolDecl*));
6436 }
6437
6438public:
6439 using qual_iterator = ObjCProtocolDecl * const *;
6440 using qual_range = llvm::iterator_range<qual_iterator>;
6441
6442 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6443 qual_iterator qual_begin() const { return getProtocolStorage(); }
6444 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
6445
6446 bool qual_empty() const { return getNumProtocols() == 0; }
6447
6448 /// Return the number of qualifying protocols in this type, or 0 if
6449 /// there are none.
6450 unsigned getNumProtocols() const {
6451 return static_cast<const T*>(this)->getNumProtocolsImpl();
6452 }
6453
6454 /// Fetch a protocol by index.
6455 ObjCProtocolDecl *getProtocol(unsigned I) const {
6456 assert(I < getNumProtocols() && "Out-of-range protocol access");
6457 return qual_begin()[I];
6458 }
6459
6460 /// Retrieve all of the protocol qualifiers.
6461 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
6462 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
6463 }
6464};
6465
6466/// Represents a type parameter type in Objective C. It can take
6467/// a list of protocols.
6468class ObjCTypeParamType : public Type,
6469 public ObjCProtocolQualifiers<ObjCTypeParamType>,
6470 public llvm::FoldingSetNode {
6471 friend class ASTContext;
6472 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
6473
6474 /// The number of protocols stored on this type.
6475 unsigned NumProtocols : 6;
6476
6477 ObjCTypeParamDecl *OTPDecl;
6478
6479 /// The protocols are stored after the ObjCTypeParamType node. In the
6480 /// canonical type, the list of protocols are sorted alphabetically
6481 /// and uniqued.
6482 ObjCProtocolDecl **getProtocolStorageImpl();
6483
6484 /// Return the number of qualifying protocols in this interface type,
6485 /// or 0 if there are none.
6486 unsigned getNumProtocolsImpl() const {
6487 return NumProtocols;
6488 }
6489
6490 void setNumProtocolsImpl(unsigned N) {
6491 NumProtocols = N;
6492 }
6493
6494 ObjCTypeParamType(const ObjCTypeParamDecl *D,
6495 QualType can,
6496 ArrayRef<ObjCProtocolDecl *> protocols);
6497
6498public:
6499 bool isSugared() const { return true; }
6500 QualType desugar() const { return getCanonicalTypeInternal(); }
6501
6502 static bool classof(const Type *T) {
6503 return T->getTypeClass() == ObjCTypeParam;
6504 }
6505
6506 void Profile(llvm::FoldingSetNodeID &ID);
6507 static void Profile(llvm::FoldingSetNodeID &ID,
6508 const ObjCTypeParamDecl *OTPDecl,
6509 QualType CanonicalType,
6510 ArrayRef<ObjCProtocolDecl *> protocols);
6511
6512 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
6513};
6514
6515/// Represents a class type in Objective C.
6516///
6517/// Every Objective C type is a combination of a base type, a set of
6518/// type arguments (optional, for parameterized classes) and a list of
6519/// protocols.
6520///
6521/// Given the following declarations:
6522/// \code
6523/// \@class C<T>;
6524/// \@protocol P;
6525/// \endcode
6526///
6527/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
6528/// with base C and no protocols.
6529///
6530/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
6531/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
6532/// protocol list.
6533/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
6534/// and protocol list [P].
6535///
6536/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
6537/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
6538/// and no protocols.
6539///
6540/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
6541/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
6542/// this should get its own sugar class to better represent the source.
6543class ObjCObjectType : public Type,
6544 public ObjCProtocolQualifiers<ObjCObjectType> {
6545 friend class ObjCProtocolQualifiers<ObjCObjectType>;
6546
6547 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
6548 // after the ObjCObjectPointerType node.
6549 // ObjCObjectType.NumProtocols - the number of protocols stored
6550 // after the type arguments of ObjCObjectPointerType node.
6551 //
6552 // These protocols are those written directly on the type. If
6553 // protocol qualifiers ever become additive, the iterators will need
6554 // to get kindof complicated.
6555 //
6556 // In the canonical object type, these are sorted alphabetically
6557 // and uniqued.
6558
6559 /// Either a BuiltinType or an InterfaceType or sugar for either.
6560 QualType BaseType;
6561
6562 /// Cached superclass type.
6563 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
6564 CachedSuperClassType;
6565
6566 QualType *getTypeArgStorage();
6567 const QualType *getTypeArgStorage() const {
6568 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
6569 }
6570
6571 ObjCProtocolDecl **getProtocolStorageImpl();
6572 /// Return the number of qualifying protocols in this interface type,
6573 /// or 0 if there are none.
6574 unsigned getNumProtocolsImpl() const {
6575 return ObjCObjectTypeBits.NumProtocols;
6576 }
6577 void setNumProtocolsImpl(unsigned N) {
6578 ObjCObjectTypeBits.NumProtocols = N;
6579 }
6580
6581protected:
6582 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
6583
6584 ObjCObjectType(QualType Canonical, QualType Base,
6585 ArrayRef<QualType> typeArgs,
6586 ArrayRef<ObjCProtocolDecl *> protocols,
6587 bool isKindOf);
6588
6589 ObjCObjectType(enum Nonce_ObjCInterface)
6590 : Type(ObjCInterface, QualType(), TypeDependence::None),
6591 BaseType(QualType(this_(), 0)) {
6592 ObjCObjectTypeBits.NumProtocols = 0;
6593 ObjCObjectTypeBits.NumTypeArgs = 0;
6594 ObjCObjectTypeBits.IsKindOf = 0;
6595 }
6596
6597 void computeSuperClassTypeSlow() const;
6598
6599public:
6600 /// Gets the base type of this object type. This is always (possibly
6601 /// sugar for) one of:
6602 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
6603 /// user, which is a typedef for an ObjCObjectPointerType)
6604 /// - the 'Class' builtin type (same caveat)
6605 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
6606 QualType getBaseType() const { return BaseType; }
6607
6608 bool isObjCId() const {
6609 return getBaseType()->isSpecificBuiltinType(K: BuiltinType::ObjCId);
6610 }
6611
6612 bool isObjCClass() const {
6613 return getBaseType()->isSpecificBuiltinType(K: BuiltinType::ObjCClass);
6614 }
6615
6616 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
6617 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
6618 bool isObjCUnqualifiedIdOrClass() const {
6619 if (!qual_empty()) return false;
6620 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
6621 return T->getKind() == BuiltinType::ObjCId ||
6622 T->getKind() == BuiltinType::ObjCClass;
6623 return false;
6624 }
6625 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
6626 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
6627
6628 /// Gets the interface declaration for this object type, if the base type
6629 /// really is an interface.
6630 ObjCInterfaceDecl *getInterface() const;
6631
6632 /// Determine whether this object type is "specialized", meaning
6633 /// that it has type arguments.
6634 bool isSpecialized() const;
6635
6636 /// Determine whether this object type was written with type arguments.
6637 bool isSpecializedAsWritten() const {
6638 return ObjCObjectTypeBits.NumTypeArgs > 0;
6639 }
6640
6641 /// Determine whether this object type is "unspecialized", meaning
6642 /// that it has no type arguments.
6643 bool isUnspecialized() const { return !isSpecialized(); }
6644
6645 /// Determine whether this object type is "unspecialized" as
6646 /// written, meaning that it has no type arguments.
6647 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6648
6649 /// Retrieve the type arguments of this object type (semantically).
6650 ArrayRef<QualType> getTypeArgs() const;
6651
6652 /// Retrieve the type arguments of this object type as they were
6653 /// written.
6654 ArrayRef<QualType> getTypeArgsAsWritten() const {
6655 return llvm::ArrayRef(getTypeArgStorage(), ObjCObjectTypeBits.NumTypeArgs);
6656 }
6657
6658 /// Whether this is a "__kindof" type as written.
6659 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
6660
6661 /// Whether this ia a "__kindof" type (semantically).
6662 bool isKindOfType() const;
6663
6664 /// Retrieve the type of the superclass of this object type.
6665 ///
6666 /// This operation substitutes any type arguments into the
6667 /// superclass of the current class type, potentially producing a
6668 /// specialization of the superclass type. Produces a null type if
6669 /// there is no superclass.
6670 QualType getSuperClassType() const {
6671 if (!CachedSuperClassType.getInt())
6672 computeSuperClassTypeSlow();
6673
6674 assert(CachedSuperClassType.getInt() && "Superclass not set?");
6675 return QualType(CachedSuperClassType.getPointer(), 0);
6676 }
6677
6678 /// Strip off the Objective-C "kindof" type and (with it) any
6679 /// protocol qualifiers.
6680 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
6681
6682 bool isSugared() const { return false; }
6683 QualType desugar() const { return QualType(this, 0); }
6684
6685 static bool classof(const Type *T) {
6686 return T->getTypeClass() == ObjCObject ||
6687 T->getTypeClass() == ObjCInterface;
6688 }
6689};
6690
6691/// A class providing a concrete implementation
6692/// of ObjCObjectType, so as to not increase the footprint of
6693/// ObjCInterfaceType. Code outside of ASTContext and the core type
6694/// system should not reference this type.
6695class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
6696 friend class ASTContext;
6697
6698 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
6699 // will need to be modified.
6700
6701 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
6702 ArrayRef<QualType> typeArgs,
6703 ArrayRef<ObjCProtocolDecl *> protocols,
6704 bool isKindOf)
6705 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
6706
6707public:
6708 void Profile(llvm::FoldingSetNodeID &ID);
6709 static void Profile(llvm::FoldingSetNodeID &ID,
6710 QualType Base,
6711 ArrayRef<QualType> typeArgs,
6712 ArrayRef<ObjCProtocolDecl *> protocols,
6713 bool isKindOf);
6714};
6715
6716inline QualType *ObjCObjectType::getTypeArgStorage() {
6717 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
6718}
6719
6720inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
6721 return reinterpret_cast<ObjCProtocolDecl**>(
6722 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
6723}
6724
6725inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
6726 return reinterpret_cast<ObjCProtocolDecl**>(
6727 static_cast<ObjCTypeParamType*>(this)+1);
6728}
6729
6730/// Interfaces are the core concept in Objective-C for object oriented design.
6731/// They basically correspond to C++ classes. There are two kinds of interface
6732/// types: normal interfaces like `NSString`, and qualified interfaces, which
6733/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6734///
6735/// ObjCInterfaceType guarantees the following properties when considered
6736/// as a subtype of its superclass, ObjCObjectType:
6737/// - There are no protocol qualifiers. To reinforce this, code which
6738/// tries to invoke the protocol methods via an ObjCInterfaceType will
6739/// fail to compile.
6740/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6741/// T->getBaseType() == QualType(T, 0).
6742class ObjCInterfaceType : public ObjCObjectType {
6743 friend class ASTContext; // ASTContext creates these.
6744 friend class ASTReader;
6745 template <class T> friend class serialization::AbstractTypeReader;
6746
6747 ObjCInterfaceDecl *Decl;
6748
6749 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6750 : ObjCObjectType(Nonce_ObjCInterface),
6751 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6752
6753public:
6754 /// Get the declaration of this interface.
6755 ObjCInterfaceDecl *getDecl() const;
6756
6757 bool isSugared() const { return false; }
6758 QualType desugar() const { return QualType(this, 0); }
6759
6760 static bool classof(const Type *T) {
6761 return T->getTypeClass() == ObjCInterface;
6762 }
6763
6764 // Nonsense to "hide" certain members of ObjCObjectType within this
6765 // class. People asking for protocols on an ObjCInterfaceType are
6766 // not going to get what they want: ObjCInterfaceTypes are
6767 // guaranteed to have no protocols.
6768 enum {
6769 qual_iterator,
6770 qual_begin,
6771 qual_end,
6772 getNumProtocols,
6773 getProtocol
6774 };
6775};
6776
6777inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6778 QualType baseType = getBaseType();
6779 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6780 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6781 return T->getDecl();
6782
6783 baseType = ObjT->getBaseType();
6784 }
6785
6786 return nullptr;
6787}
6788
6789/// Represents a pointer to an Objective C object.
6790///
6791/// These are constructed from pointer declarators when the pointee type is
6792/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6793/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6794/// and 'Class<P>' are translated into these.
6795///
6796/// Pointers to pointers to Objective C objects are still PointerTypes;
6797/// only the first level of pointer gets it own type implementation.
6798class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6799 friend class ASTContext; // ASTContext creates these.
6800
6801 QualType PointeeType;
6802
6803 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6804 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6805 PointeeType(Pointee) {}
6806
6807public:
6808 /// Gets the type pointed to by this ObjC pointer.
6809 /// The result will always be an ObjCObjectType or sugar thereof.
6810 QualType getPointeeType() const { return PointeeType; }
6811
6812 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6813 ///
6814 /// This method is equivalent to getPointeeType() except that
6815 /// it discards any typedefs (or other sugar) between this
6816 /// type and the "outermost" object type. So for:
6817 /// \code
6818 /// \@class A; \@protocol P; \@protocol Q;
6819 /// typedef A<P> AP;
6820 /// typedef A A1;
6821 /// typedef A1<P> A1P;
6822 /// typedef A1P<Q> A1PQ;
6823 /// \endcode
6824 /// For 'A*', getObjectType() will return 'A'.
6825 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6826 /// For 'AP*', getObjectType() will return 'A<P>'.
6827 /// For 'A1*', getObjectType() will return 'A'.
6828 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6829 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6830 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6831 /// adding protocols to a protocol-qualified base discards the
6832 /// old qualifiers (for now). But if it didn't, getObjectType()
6833 /// would return 'A1P<Q>' (and we'd have to make iterating over
6834 /// qualifiers more complicated).
6835 const ObjCObjectType *getObjectType() const {
6836 return PointeeType->castAs<ObjCObjectType>();
6837 }
6838
6839 /// If this pointer points to an Objective C
6840 /// \@interface type, gets the type for that interface. Any protocol
6841 /// qualifiers on the interface are ignored.
6842 ///
6843 /// \return null if the base type for this pointer is 'id' or 'Class'
6844 const ObjCInterfaceType *getInterfaceType() const;
6845
6846 /// If this pointer points to an Objective \@interface
6847 /// type, gets the declaration for that interface.
6848 ///
6849 /// \return null if the base type for this pointer is 'id' or 'Class'
6850 ObjCInterfaceDecl *getInterfaceDecl() const {
6851 return getObjectType()->getInterface();
6852 }
6853
6854 /// True if this is equivalent to the 'id' type, i.e. if
6855 /// its object type is the primitive 'id' type with no protocols.
6856 bool isObjCIdType() const {
6857 return getObjectType()->isObjCUnqualifiedId();
6858 }
6859
6860 /// True if this is equivalent to the 'Class' type,
6861 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6862 bool isObjCClassType() const {
6863 return getObjectType()->isObjCUnqualifiedClass();
6864 }
6865
6866 /// True if this is equivalent to the 'id' or 'Class' type,
6867 bool isObjCIdOrClassType() const {
6868 return getObjectType()->isObjCUnqualifiedIdOrClass();
6869 }
6870
6871 /// True if this is equivalent to 'id<P>' for some non-empty set of
6872 /// protocols.
6873 bool isObjCQualifiedIdType() const {
6874 return getObjectType()->isObjCQualifiedId();
6875 }
6876
6877 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6878 /// protocols.
6879 bool isObjCQualifiedClassType() const {
6880 return getObjectType()->isObjCQualifiedClass();
6881 }
6882
6883 /// Whether this is a "__kindof" type.
6884 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6885
6886 /// Whether this type is specialized, meaning that it has type arguments.
6887 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6888
6889 /// Whether this type is specialized, meaning that it has type arguments.
6890 bool isSpecializedAsWritten() const {
6891 return getObjectType()->isSpecializedAsWritten();
6892 }
6893
6894 /// Whether this type is unspecialized, meaning that is has no type arguments.
6895 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6896
6897 /// Determine whether this object type is "unspecialized" as
6898 /// written, meaning that it has no type arguments.
6899 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6900
6901 /// Retrieve the type arguments for this type.
6902 ArrayRef<QualType> getTypeArgs() const {
6903 return getObjectType()->getTypeArgs();
6904 }
6905
6906 /// Retrieve the type arguments for this type.
6907 ArrayRef<QualType> getTypeArgsAsWritten() const {
6908 return getObjectType()->getTypeArgsAsWritten();
6909 }
6910
6911 /// An iterator over the qualifiers on the object type. Provided
6912 /// for convenience. This will always iterate over the full set of
6913 /// protocols on a type, not just those provided directly.
6914 using qual_iterator = ObjCObjectType::qual_iterator;
6915 using qual_range = llvm::iterator_range<qual_iterator>;
6916
6917 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6918
6919 qual_iterator qual_begin() const {
6920 return getObjectType()->qual_begin();
6921 }
6922
6923 qual_iterator qual_end() const {
6924 return getObjectType()->qual_end();
6925 }
6926
6927 bool qual_empty() const { return getObjectType()->qual_empty(); }
6928
6929 /// Return the number of qualifying protocols on the object type.
6930 unsigned getNumProtocols() const {
6931 return getObjectType()->getNumProtocols();
6932 }
6933
6934 /// Retrieve a qualifying protocol by index on the object type.
6935 ObjCProtocolDecl *getProtocol(unsigned I) const {
6936 return getObjectType()->getProtocol(I);
6937 }
6938
6939 bool isSugared() const { return false; }
6940 QualType desugar() const { return QualType(this, 0); }
6941
6942 /// Retrieve the type of the superclass of this object pointer type.
6943 ///
6944 /// This operation substitutes any type arguments into the
6945 /// superclass of the current class type, potentially producing a
6946 /// pointer to a specialization of the superclass type. Produces a
6947 /// null type if there is no superclass.
6948 QualType getSuperClassType() const;
6949
6950 /// Strip off the Objective-C "kindof" type and (with it) any
6951 /// protocol qualifiers.
6952 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6953 const ASTContext &ctx) const;
6954
6955 void Profile(llvm::FoldingSetNodeID &ID) {
6956 Profile(ID, T: getPointeeType());
6957 }
6958
6959 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6960 ID.AddPointer(Ptr: T.getAsOpaquePtr());
6961 }
6962
6963 static bool classof(const Type *T) {
6964 return T->getTypeClass() == ObjCObjectPointer;
6965 }
6966};
6967
6968class AtomicType : public Type, public llvm::FoldingSetNode {
6969 friend class ASTContext; // ASTContext creates these.
6970
6971 QualType ValueType;
6972
6973 AtomicType(QualType ValTy, QualType Canonical)
6974 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6975
6976public:
6977 /// Gets the type contained by this atomic type, i.e.
6978 /// the type returned by performing an atomic load of this atomic type.
6979 QualType getValueType() const { return ValueType; }
6980
6981 bool isSugared() const { return false; }
6982 QualType desugar() const { return QualType(this, 0); }
6983
6984 void Profile(llvm::FoldingSetNodeID &ID) {
6985 Profile(ID, T: getValueType());
6986 }
6987
6988 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6989 ID.AddPointer(Ptr: T.getAsOpaquePtr());
6990 }
6991
6992 static bool classof(const Type *T) {
6993 return T->getTypeClass() == Atomic;
6994 }
6995};
6996
6997/// PipeType - OpenCL20.
6998class PipeType : public Type, public llvm::FoldingSetNode {
6999 friend class ASTContext; // ASTContext creates these.
7000
7001 QualType ElementType;
7002 bool isRead;
7003
7004 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
7005 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
7006 ElementType(elemType), isRead(isRead) {}
7007
7008public:
7009 QualType getElementType() const { return ElementType; }
7010
7011 bool isSugared() const { return false; }
7012
7013 QualType desugar() const { return QualType(this, 0); }
7014
7015 void Profile(llvm::FoldingSetNodeID &ID) {
7016 Profile(ID, T: getElementType(), isRead: isReadOnly());
7017 }
7018
7019 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
7020 ID.AddPointer(Ptr: T.getAsOpaquePtr());
7021 ID.AddBoolean(B: isRead);
7022 }
7023
7024 static bool classof(const Type *T) {
7025 return T->getTypeClass() == Pipe;
7026 }
7027
7028 bool isReadOnly() const { return isRead; }
7029};
7030
7031/// A fixed int type of a specified bitwidth.
7032class BitIntType final : public Type, public llvm::FoldingSetNode {
7033 friend class ASTContext;
7034 LLVM_PREFERRED_TYPE(bool)
7035 unsigned IsUnsigned : 1;
7036 unsigned NumBits : 24;
7037
7038protected:
7039 BitIntType(bool isUnsigned, unsigned NumBits);
7040
7041public:
7042 bool isUnsigned() const { return IsUnsigned; }
7043 bool isSigned() const { return !IsUnsigned; }
7044 unsigned getNumBits() const { return NumBits; }
7045
7046 bool isSugared() const { return false; }
7047 QualType desugar() const { return QualType(this, 0); }
7048
7049 void Profile(llvm::FoldingSetNodeID &ID) const {
7050 Profile(ID, IsUnsigned: isUnsigned(), NumBits: getNumBits());
7051 }
7052
7053 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
7054 unsigned NumBits) {
7055 ID.AddBoolean(B: IsUnsigned);
7056 ID.AddInteger(I: NumBits);
7057 }
7058
7059 static bool classof(const Type *T) { return T->getTypeClass() == BitInt; }
7060};
7061
7062class DependentBitIntType final : public Type, public llvm::FoldingSetNode {
7063 friend class ASTContext;
7064 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
7065
7066protected:
7067 DependentBitIntType(bool IsUnsigned, Expr *NumBits);
7068
7069public:
7070 bool isUnsigned() const;
7071 bool isSigned() const { return !isUnsigned(); }
7072 Expr *getNumBitsExpr() const;
7073
7074 bool isSugared() const { return false; }
7075 QualType desugar() const { return QualType(this, 0); }
7076
7077 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
7078 Profile(ID, Context, IsUnsigned: isUnsigned(), NumBitsExpr: getNumBitsExpr());
7079 }
7080 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
7081 bool IsUnsigned, Expr *NumBitsExpr);
7082
7083 static bool classof(const Type *T) {
7084 return T->getTypeClass() == DependentBitInt;
7085 }
7086};
7087
7088/// A qualifier set is used to build a set of qualifiers.
7089class QualifierCollector : public Qualifiers {
7090public:
7091 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
7092
7093 /// Collect any qualifiers on the given type and return an
7094 /// unqualified type. The qualifiers are assumed to be consistent
7095 /// with those already in the type.
7096 const Type *strip(QualType type) {
7097 addFastQualifiers(mask: type.getLocalFastQualifiers());
7098 if (!type.hasLocalNonFastQualifiers())
7099 return type.getTypePtrUnsafe();
7100
7101 const ExtQuals *extQuals = type.getExtQualsUnsafe();
7102 addConsistentQualifiers(qs: extQuals->getQualifiers());
7103 return extQuals->getBaseType();
7104 }
7105
7106 /// Apply the collected qualifiers to the given type.
7107 QualType apply(const ASTContext &Context, QualType QT) const;
7108
7109 /// Apply the collected qualifiers to the given type.
7110 QualType apply(const ASTContext &Context, const Type* T) const;
7111};
7112
7113/// A container of type source information.
7114///
7115/// A client can read the relevant info using TypeLoc wrappers, e.g:
7116/// @code
7117/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
7118/// TL.getBeginLoc().print(OS, SrcMgr);
7119/// @endcode
7120class alignas(8) TypeSourceInfo {
7121 // Contains a memory block after the class, used for type source information,
7122 // allocated by ASTContext.
7123 friend class ASTContext;
7124
7125 QualType Ty;
7126
7127 TypeSourceInfo(QualType ty, size_t DataSize); // implemented in TypeLoc.h
7128
7129public:
7130 /// Return the type wrapped by this type source info.
7131 QualType getType() const { return Ty; }
7132
7133 /// Return the TypeLoc wrapper for the type source info.
7134 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
7135
7136 /// Override the type stored in this TypeSourceInfo. Use with caution!
7137 void overrideType(QualType T) { Ty = T; }
7138};
7139
7140// Inline function definitions.
7141
7142inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
7143 SplitQualType desugar =
7144 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
7145 desugar.Quals.addConsistentQualifiers(qs: Quals);
7146 return desugar;
7147}
7148
7149inline const Type *QualType::getTypePtr() const {
7150 return getCommonPtr()->BaseType;
7151}
7152
7153inline const Type *QualType::getTypePtrOrNull() const {
7154 return (isNull() ? nullptr : getCommonPtr()->BaseType);
7155}
7156
7157inline bool QualType::isReferenceable() const {
7158 // C++ [defns.referenceable]
7159 // type that is either an object type, a function type that does not have
7160 // cv-qualifiers or a ref-qualifier, or a reference type.
7161 const Type &Self = **this;
7162 if (Self.isObjectType() || Self.isReferenceType())
7163 return true;
7164 if (const auto *F = Self.getAs<FunctionProtoType>())
7165 return F->getMethodQuals().empty() && F->getRefQualifier() == RQ_None;
7166
7167 return false;
7168}
7169
7170inline SplitQualType QualType::split() const {
7171 if (!hasLocalNonFastQualifiers())
7172 return SplitQualType(getTypePtrUnsafe(),
7173 Qualifiers::fromFastMask(Mask: getLocalFastQualifiers()));
7174
7175 const ExtQuals *eq = getExtQualsUnsafe();
7176 Qualifiers qs = eq->getQualifiers();
7177 qs.addFastQualifiers(mask: getLocalFastQualifiers());
7178 return SplitQualType(eq->getBaseType(), qs);
7179}
7180
7181inline Qualifiers QualType::getLocalQualifiers() const {
7182 Qualifiers Quals;
7183 if (hasLocalNonFastQualifiers())
7184 Quals = getExtQualsUnsafe()->getQualifiers();
7185 Quals.addFastQualifiers(mask: getLocalFastQualifiers());
7186 return Quals;
7187}
7188
7189inline Qualifiers QualType::getQualifiers() const {
7190 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
7191 quals.addFastQualifiers(mask: getLocalFastQualifiers());
7192 return quals;
7193}
7194
7195inline unsigned QualType::getCVRQualifiers() const {
7196 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
7197 cvr |= getLocalCVRQualifiers();
7198 return cvr;
7199}
7200
7201inline QualType QualType::getCanonicalType() const {
7202 QualType canon = getCommonPtr()->CanonicalType;
7203 return canon.withFastQualifiers(TQs: getLocalFastQualifiers());
7204}
7205
7206inline bool QualType::isCanonical() const {
7207 return getTypePtr()->isCanonicalUnqualified();
7208}
7209
7210inline bool QualType::isCanonicalAsParam() const {
7211 if (!isCanonical()) return false;
7212 if (hasLocalQualifiers()) return false;
7213
7214 const Type *T = getTypePtr();
7215 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
7216 return false;
7217
7218 return !isa<FunctionType>(T) &&
7219 (!isa<ArrayType>(T) || isa<ArrayParameterType>(T));
7220}
7221
7222inline bool QualType::isConstQualified() const {
7223 return isLocalConstQualified() ||
7224 getCommonPtr()->CanonicalType.isLocalConstQualified();
7225}
7226
7227inline bool QualType::isRestrictQualified() const {
7228 return isLocalRestrictQualified() ||
7229 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
7230}
7231
7232
7233inline bool QualType::isVolatileQualified() const {
7234 return isLocalVolatileQualified() ||
7235 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
7236}
7237
7238inline bool QualType::hasQualifiers() const {
7239 return hasLocalQualifiers() ||
7240 getCommonPtr()->CanonicalType.hasLocalQualifiers();
7241}
7242
7243inline QualType QualType::getUnqualifiedType() const {
7244 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
7245 return QualType(getTypePtr(), 0);
7246
7247 return QualType(getSplitUnqualifiedTypeImpl(type: *this).Ty, 0);
7248}
7249
7250inline SplitQualType QualType::getSplitUnqualifiedType() const {
7251 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
7252 return split();
7253
7254 return getSplitUnqualifiedTypeImpl(type: *this);
7255}
7256
7257inline void QualType::removeLocalConst() {
7258 removeLocalFastQualifiers(Mask: Qualifiers::Const);
7259}
7260
7261inline void QualType::removeLocalRestrict() {
7262 removeLocalFastQualifiers(Mask: Qualifiers::Restrict);
7263}
7264
7265inline void QualType::removeLocalVolatile() {
7266 removeLocalFastQualifiers(Mask: Qualifiers::Volatile);
7267}
7268
7269/// Check if this type has any address space qualifier.
7270inline bool QualType::hasAddressSpace() const {
7271 return getQualifiers().hasAddressSpace();
7272}
7273
7274/// Return the address space of this type.
7275inline LangAS QualType::getAddressSpace() const {
7276 return getQualifiers().getAddressSpace();
7277}
7278
7279/// Return the gc attribute of this type.
7280inline Qualifiers::GC QualType::getObjCGCAttr() const {
7281 return getQualifiers().getObjCGCAttr();
7282}
7283
7284inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
7285 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
7286 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
7287 return false;
7288}
7289
7290inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
7291 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
7292 return hasNonTrivialToPrimitiveDestructCUnion(RD);
7293 return false;
7294}
7295
7296inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
7297 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
7298 return hasNonTrivialToPrimitiveCopyCUnion(RD);
7299 return false;
7300}
7301
7302inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
7303 if (const auto *PT = t.getAs<PointerType>()) {
7304 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
7305 return FT->getExtInfo();
7306 } else if (const auto *FT = t.getAs<FunctionType>())
7307 return FT->getExtInfo();
7308
7309 return FunctionType::ExtInfo();
7310}
7311
7312inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
7313 return getFunctionExtInfo(t: *t);
7314}
7315
7316/// Determine whether this type is more
7317/// qualified than the Other type. For example, "const volatile int"
7318/// is more qualified than "const int", "volatile int", and
7319/// "int". However, it is not more qualified than "const volatile
7320/// int".
7321inline bool QualType::isMoreQualifiedThan(QualType other) const {
7322 Qualifiers MyQuals = getQualifiers();
7323 Qualifiers OtherQuals = other.getQualifiers();
7324 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(other: OtherQuals));
7325}
7326
7327/// Determine whether this type is at last
7328/// as qualified as the Other type. For example, "const volatile
7329/// int" is at least as qualified as "const int", "volatile int",
7330/// "int", and "const volatile int".
7331inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
7332 Qualifiers OtherQuals = other.getQualifiers();
7333
7334 // Ignore __unaligned qualifier if this type is a void.
7335 if (getUnqualifiedType()->isVoidType())
7336 OtherQuals.removeUnaligned();
7337
7338 return getQualifiers().compatiblyIncludes(other: OtherQuals);
7339}
7340
7341/// If Type is a reference type (e.g., const
7342/// int&), returns the type that the reference refers to ("const
7343/// int"). Otherwise, returns the type itself. This routine is used
7344/// throughout Sema to implement C++ 5p6:
7345///
7346/// If an expression initially has the type "reference to T" (8.3.2,
7347/// 8.5.3), the type is adjusted to "T" prior to any further
7348/// analysis, the expression designates the object or function
7349/// denoted by the reference, and the expression is an lvalue.
7350inline QualType QualType::getNonReferenceType() const {
7351 if (const auto *RefType = (*this)->getAs<ReferenceType>())
7352 return RefType->getPointeeType();
7353 else
7354 return *this;
7355}
7356
7357inline bool QualType::isCForbiddenLValueType() const {
7358 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
7359 getTypePtr()->isFunctionType());
7360}
7361
7362/// Tests whether the type is categorized as a fundamental type.
7363///
7364/// \returns True for types specified in C++0x [basic.fundamental].
7365inline bool Type::isFundamentalType() const {
7366 return isVoidType() ||
7367 isNullPtrType() ||
7368 // FIXME: It's really annoying that we don't have an
7369 // 'isArithmeticType()' which agrees with the standard definition.
7370 (isArithmeticType() && !isEnumeralType());
7371}
7372
7373/// Tests whether the type is categorized as a compound type.
7374///
7375/// \returns True for types specified in C++0x [basic.compound].
7376inline bool Type::isCompoundType() const {
7377 // C++0x [basic.compound]p1:
7378 // Compound types can be constructed in the following ways:
7379 // -- arrays of objects of a given type [...];
7380 return isArrayType() ||
7381 // -- functions, which have parameters of given types [...];
7382 isFunctionType() ||
7383 // -- pointers to void or objects or functions [...];
7384 isPointerType() ||
7385 // -- references to objects or functions of a given type. [...]
7386 isReferenceType() ||
7387 // -- classes containing a sequence of objects of various types, [...];
7388 isRecordType() ||
7389 // -- unions, which are classes capable of containing objects of different
7390 // types at different times;
7391 isUnionType() ||
7392 // -- enumerations, which comprise a set of named constant values. [...];
7393 isEnumeralType() ||
7394 // -- pointers to non-static class members, [...].
7395 isMemberPointerType();
7396}
7397
7398inline bool Type::isFunctionType() const {
7399 return isa<FunctionType>(CanonicalType);
7400}
7401
7402inline bool Type::isPointerType() const {
7403 return isa<PointerType>(CanonicalType);
7404}
7405
7406inline bool Type::isAnyPointerType() const {
7407 return isPointerType() || isObjCObjectPointerType();
7408}
7409
7410inline bool Type::isBlockPointerType() const {
7411 return isa<BlockPointerType>(CanonicalType);
7412}
7413
7414inline bool Type::isReferenceType() const {
7415 return isa<ReferenceType>(CanonicalType);
7416}
7417
7418inline bool Type::isLValueReferenceType() const {
7419 return isa<LValueReferenceType>(CanonicalType);
7420}
7421
7422inline bool Type::isRValueReferenceType() const {
7423 return isa<RValueReferenceType>(CanonicalType);
7424}
7425
7426inline bool Type::isObjectPointerType() const {
7427 // Note: an "object pointer type" is not the same thing as a pointer to an
7428 // object type; rather, it is a pointer to an object type or a pointer to cv
7429 // void.
7430 if (const auto *T = getAs<PointerType>())
7431 return !T->getPointeeType()->isFunctionType();
7432 else
7433 return false;
7434}
7435
7436inline bool Type::isFunctionPointerType() const {
7437 if (const auto *T = getAs<PointerType>())
7438 return T->getPointeeType()->isFunctionType();
7439 else
7440 return false;
7441}
7442
7443inline bool Type::isFunctionReferenceType() const {
7444 if (const auto *T = getAs<ReferenceType>())
7445 return T->getPointeeType()->isFunctionType();
7446 else
7447 return false;
7448}
7449
7450inline bool Type::isMemberPointerType() const {
7451 return isa<MemberPointerType>(CanonicalType);
7452}
7453
7454inline bool Type::isMemberFunctionPointerType() const {
7455 if (const auto *T = getAs<MemberPointerType>())
7456 return T->isMemberFunctionPointer();
7457 else
7458 return false;
7459}
7460
7461inline bool Type::isMemberDataPointerType() const {
7462 if (const auto *T = getAs<MemberPointerType>())
7463 return T->isMemberDataPointer();
7464 else
7465 return false;
7466}
7467
7468inline bool Type::isArrayType() const {
7469 return isa<ArrayType>(CanonicalType);
7470}
7471
7472inline bool Type::isConstantArrayType() const {
7473 return isa<ConstantArrayType>(CanonicalType);
7474}
7475
7476inline bool Type::isIncompleteArrayType() const {
7477 return isa<IncompleteArrayType>(CanonicalType);
7478}
7479
7480inline bool Type::isVariableArrayType() const {
7481 return isa<VariableArrayType>(CanonicalType);
7482}
7483
7484inline bool Type::isArrayParameterType() const {
7485 return isa<ArrayParameterType>(CanonicalType);
7486}
7487
7488inline bool Type::isDependentSizedArrayType() const {
7489 return isa<DependentSizedArrayType>(CanonicalType);
7490}
7491
7492inline bool Type::isBuiltinType() const {
7493 return isa<BuiltinType>(CanonicalType);
7494}
7495
7496inline bool Type::isRecordType() const {
7497 return isa<RecordType>(CanonicalType);
7498}
7499
7500inline bool Type::isEnumeralType() const {
7501 return isa<EnumType>(CanonicalType);
7502}
7503
7504inline bool Type::isAnyComplexType() const {
7505 return isa<ComplexType>(CanonicalType);
7506}
7507
7508inline bool Type::isVectorType() const {
7509 return isa<VectorType>(CanonicalType);
7510}
7511
7512inline bool Type::isExtVectorType() const {
7513 return isa<ExtVectorType>(CanonicalType);
7514}
7515
7516inline bool Type::isExtVectorBoolType() const {
7517 if (!isExtVectorType())
7518 return false;
7519 return cast<ExtVectorType>(CanonicalType)->getElementType()->isBooleanType();
7520}
7521
7522inline bool Type::isMatrixType() const {
7523 return isa<MatrixType>(CanonicalType);
7524}
7525
7526inline bool Type::isConstantMatrixType() const {
7527 return isa<ConstantMatrixType>(CanonicalType);
7528}
7529
7530inline bool Type::isDependentAddressSpaceType() const {
7531 return isa<DependentAddressSpaceType>(CanonicalType);
7532}
7533
7534inline bool Type::isObjCObjectPointerType() const {
7535 return isa<ObjCObjectPointerType>(CanonicalType);
7536}
7537
7538inline bool Type::isObjCObjectType() const {
7539 return isa<ObjCObjectType>(CanonicalType);
7540}
7541
7542inline bool Type::isObjCObjectOrInterfaceType() const {
7543 return isa<ObjCInterfaceType>(CanonicalType) ||
7544 isa<ObjCObjectType>(CanonicalType);
7545}
7546
7547inline bool Type::isAtomicType() const {
7548 return isa<AtomicType>(CanonicalType);
7549}
7550
7551inline bool Type::isUndeducedAutoType() const {
7552 return isa<AutoType>(CanonicalType);
7553}
7554
7555inline bool Type::isObjCQualifiedIdType() const {
7556 if (const auto *OPT = getAs<ObjCObjectPointerType>())
7557 return OPT->isObjCQualifiedIdType();
7558 return false;
7559}
7560
7561inline bool Type::isObjCQualifiedClassType() const {
7562 if (const auto *OPT = getAs<ObjCObjectPointerType>())
7563 return OPT->isObjCQualifiedClassType();
7564 return false;
7565}
7566
7567inline bool Type::isObjCIdType() const {
7568 if (const auto *OPT = getAs<ObjCObjectPointerType>())
7569 return OPT->isObjCIdType();
7570 return false;
7571}
7572
7573inline bool Type::isObjCClassType() const {
7574 if (const auto *OPT = getAs<ObjCObjectPointerType>())
7575 return OPT->isObjCClassType();
7576 return false;
7577}
7578
7579inline bool Type::isObjCSelType() const {
7580 if (const auto *OPT = getAs<PointerType>())
7581 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
7582 return false;
7583}
7584
7585inline bool Type::isObjCBuiltinType() const {
7586 return isObjCIdType() || isObjCClassType() || isObjCSelType();
7587}
7588
7589inline bool Type::isDecltypeType() const {
7590 return isa<DecltypeType>(this);
7591}
7592
7593#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7594 inline bool Type::is##Id##Type() const { \
7595 return isSpecificBuiltinType(BuiltinType::Id); \
7596 }
7597#include "clang/Basic/OpenCLImageTypes.def"
7598
7599inline bool Type::isSamplerT() const {
7600 return isSpecificBuiltinType(K: BuiltinType::OCLSampler);
7601}
7602
7603inline bool Type::isEventT() const {
7604 return isSpecificBuiltinType(K: BuiltinType::OCLEvent);
7605}
7606
7607inline bool Type::isClkEventT() const {
7608 return isSpecificBuiltinType(K: BuiltinType::OCLClkEvent);
7609}
7610
7611inline bool Type::isQueueT() const {
7612 return isSpecificBuiltinType(K: BuiltinType::OCLQueue);
7613}
7614
7615inline bool Type::isReserveIDT() const {
7616 return isSpecificBuiltinType(K: BuiltinType::OCLReserveID);
7617}
7618
7619inline bool Type::isImageType() const {
7620#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
7621 return
7622#include "clang/Basic/OpenCLImageTypes.def"
7623 false; // end boolean or operation
7624}
7625
7626inline bool Type::isPipeType() const {
7627 return isa<PipeType>(CanonicalType);
7628}
7629
7630inline bool Type::isBitIntType() const {
7631 return isa<BitIntType>(CanonicalType);
7632}
7633
7634#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7635 inline bool Type::is##Id##Type() const { \
7636 return isSpecificBuiltinType(BuiltinType::Id); \
7637 }
7638#include "clang/Basic/OpenCLExtensionTypes.def"
7639
7640inline bool Type::isOCLIntelSubgroupAVCType() const {
7641#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
7642 isOCLIntelSubgroupAVC##Id##Type() ||
7643 return
7644#include "clang/Basic/OpenCLExtensionTypes.def"
7645 false; // end of boolean or operation
7646}
7647
7648inline bool Type::isOCLExtOpaqueType() const {
7649#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
7650 return
7651#include "clang/Basic/OpenCLExtensionTypes.def"
7652 false; // end of boolean or operation
7653}
7654
7655inline bool Type::isOpenCLSpecificType() const {
7656 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
7657 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
7658}
7659
7660inline bool Type::isTemplateTypeParmType() const {
7661 return isa<TemplateTypeParmType>(CanonicalType);
7662}
7663
7664inline bool Type::isSpecificBuiltinType(unsigned K) const {
7665 if (const BuiltinType *BT = getAs<BuiltinType>()) {
7666 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
7667 }
7668 return false;
7669}
7670
7671inline bool Type::isPlaceholderType() const {
7672 if (const auto *BT = dyn_cast<BuiltinType>(this))
7673 return BT->isPlaceholderType();
7674 return false;
7675}
7676
7677inline const BuiltinType *Type::getAsPlaceholderType() const {
7678 if (const auto *BT = dyn_cast<BuiltinType>(this))
7679 if (BT->isPlaceholderType())
7680 return BT;
7681 return nullptr;
7682}
7683
7684inline bool Type::isSpecificPlaceholderType(unsigned K) const {
7685 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
7686 return isSpecificBuiltinType(K);
7687}
7688
7689inline bool Type::isNonOverloadPlaceholderType() const {
7690 if (const auto *BT = dyn_cast<BuiltinType>(this))
7691 return BT->isNonOverloadPlaceholderType();
7692 return false;
7693}
7694
7695inline bool Type::isVoidType() const {
7696 return isSpecificBuiltinType(K: BuiltinType::Void);
7697}
7698
7699inline bool Type::isHalfType() const {
7700 // FIXME: Should we allow complex __fp16? Probably not.
7701 return isSpecificBuiltinType(K: BuiltinType::Half);
7702}
7703
7704inline bool Type::isFloat16Type() const {
7705 return isSpecificBuiltinType(K: BuiltinType::Float16);
7706}
7707
7708inline bool Type::isFloat32Type() const {
7709 return isSpecificBuiltinType(K: BuiltinType::Float);
7710}
7711
7712inline bool Type::isDoubleType() const {
7713 return isSpecificBuiltinType(K: BuiltinType::Double);
7714}
7715
7716inline bool Type::isBFloat16Type() const {
7717 return isSpecificBuiltinType(K: BuiltinType::BFloat16);
7718}
7719
7720inline bool Type::isFloat128Type() const {
7721 return isSpecificBuiltinType(K: BuiltinType::Float128);
7722}
7723
7724inline bool Type::isIbm128Type() const {
7725 return isSpecificBuiltinType(K: BuiltinType::Ibm128);
7726}
7727
7728inline bool Type::isNullPtrType() const {
7729 return isSpecificBuiltinType(K: BuiltinType::NullPtr);
7730}
7731
7732bool IsEnumDeclComplete(EnumDecl *);
7733bool IsEnumDeclScoped(EnumDecl *);
7734
7735inline bool Type::isIntegerType() const {
7736 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7737 return BT->getKind() >= BuiltinType::Bool &&
7738 BT->getKind() <= BuiltinType::Int128;
7739 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
7740 // Incomplete enum types are not treated as integer types.
7741 // FIXME: In C++, enum types are never integer types.
7742 return IsEnumDeclComplete(ET->getDecl()) &&
7743 !IsEnumDeclScoped(ET->getDecl());
7744 }
7745 return isBitIntType();
7746}
7747
7748inline bool Type::isFixedPointType() const {
7749 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7750 return BT->getKind() >= BuiltinType::ShortAccum &&
7751 BT->getKind() <= BuiltinType::SatULongFract;
7752 }
7753 return false;
7754}
7755
7756inline bool Type::isFixedPointOrIntegerType() const {
7757 return isFixedPointType() || isIntegerType();
7758}
7759
7760inline bool Type::isConvertibleToFixedPointType() const {
7761 return isRealFloatingType() || isFixedPointOrIntegerType();
7762}
7763
7764inline bool Type::isSaturatedFixedPointType() const {
7765 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7766 return BT->getKind() >= BuiltinType::SatShortAccum &&
7767 BT->getKind() <= BuiltinType::SatULongFract;
7768 }
7769 return false;
7770}
7771
7772inline bool Type::isUnsaturatedFixedPointType() const {
7773 return isFixedPointType() && !isSaturatedFixedPointType();
7774}
7775
7776inline bool Type::isSignedFixedPointType() const {
7777 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7778 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7779 BT->getKind() <= BuiltinType::LongAccum) ||
7780 (BT->getKind() >= BuiltinType::ShortFract &&
7781 BT->getKind() <= BuiltinType::LongFract) ||
7782 (BT->getKind() >= BuiltinType::SatShortAccum &&
7783 BT->getKind() <= BuiltinType::SatLongAccum) ||
7784 (BT->getKind() >= BuiltinType::SatShortFract &&
7785 BT->getKind() <= BuiltinType::SatLongFract));
7786 }
7787 return false;
7788}
7789
7790inline bool Type::isUnsignedFixedPointType() const {
7791 return isFixedPointType() && !isSignedFixedPointType();
7792}
7793
7794inline bool Type::isScalarType() const {
7795 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7796 return BT->getKind() > BuiltinType::Void &&
7797 BT->getKind() <= BuiltinType::NullPtr;
7798 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7799 // Enums are scalar types, but only if they are defined. Incomplete enums
7800 // are not treated as scalar types.
7801 return IsEnumDeclComplete(ET->getDecl());
7802 return isa<PointerType>(CanonicalType) ||
7803 isa<BlockPointerType>(CanonicalType) ||
7804 isa<MemberPointerType>(CanonicalType) ||
7805 isa<ComplexType>(CanonicalType) ||
7806 isa<ObjCObjectPointerType>(CanonicalType) ||
7807 isBitIntType();
7808}
7809
7810inline bool Type::isIntegralOrEnumerationType() const {
7811 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7812 return BT->getKind() >= BuiltinType::Bool &&
7813 BT->getKind() <= BuiltinType::Int128;
7814
7815 // Check for a complete enum type; incomplete enum types are not properly an
7816 // enumeration type in the sense required here.
7817 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7818 return IsEnumDeclComplete(ET->getDecl());
7819
7820 return isBitIntType();
7821}
7822
7823inline bool Type::isBooleanType() const {
7824 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7825 return BT->getKind() == BuiltinType::Bool;
7826 return false;
7827}
7828
7829inline bool Type::isUndeducedType() const {
7830 auto *DT = getContainedDeducedType();
7831 return DT && !DT->isDeduced();
7832}
7833
7834/// Determines whether this is a type for which one can define
7835/// an overloaded operator.
7836inline bool Type::isOverloadableType() const {
7837 return isDependentType() || isRecordType() || isEnumeralType();
7838}
7839
7840/// Determines whether this type is written as a typedef-name.
7841inline bool Type::isTypedefNameType() const {
7842 if (getAs<TypedefType>())
7843 return true;
7844 if (auto *TST = getAs<TemplateSpecializationType>())
7845 return TST->isTypeAlias();
7846 return false;
7847}
7848
7849/// Determines whether this type can decay to a pointer type.
7850inline bool Type::canDecayToPointerType() const {
7851 return isFunctionType() || (isArrayType() && !isArrayParameterType());
7852}
7853
7854inline bool Type::hasPointerRepresentation() const {
7855 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7856 isObjCObjectPointerType() || isNullPtrType());
7857}
7858
7859inline bool Type::hasObjCPointerRepresentation() const {
7860 return isObjCObjectPointerType();
7861}
7862
7863inline const Type *Type::getBaseElementTypeUnsafe() const {
7864 const Type *type = this;
7865 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7866 type = arrayType->getElementType().getTypePtr();
7867 return type;
7868}
7869
7870inline const Type *Type::getPointeeOrArrayElementType() const {
7871 const Type *type = this;
7872 if (type->isAnyPointerType())
7873 return type->getPointeeType().getTypePtr();
7874 else if (type->isArrayType())
7875 return type->getBaseElementTypeUnsafe();
7876 return type;
7877}
7878/// Insertion operator for partial diagnostics. This allows sending adress
7879/// spaces into a diagnostic with <<.
7880inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7881 LangAS AS) {
7882 PD.AddTaggedVal(V: llvm::to_underlying(AS),
7883 Kind: DiagnosticsEngine::ArgumentKind::ak_addrspace);
7884 return PD;
7885}
7886
7887/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7888/// into a diagnostic with <<.
7889inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7890 Qualifiers Q) {
7891 PD.AddTaggedVal(V: Q.getAsOpaqueValue(),
7892 Kind: DiagnosticsEngine::ArgumentKind::ak_qual);
7893 return PD;
7894}
7895
7896/// Insertion operator for partial diagnostics. This allows sending QualType's
7897/// into a diagnostic with <<.
7898inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7899 QualType T) {
7900 PD.AddTaggedVal(V: reinterpret_cast<uint64_t>(T.getAsOpaquePtr()),
7901 Kind: DiagnosticsEngine::ak_qualtype);
7902 return PD;
7903}
7904
7905// Helper class template that is used by Type::getAs to ensure that one does
7906// not try to look through a qualified type to get to an array type.
7907template <typename T>
7908using TypeIsArrayType =
7909 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7910 std::is_base_of<ArrayType, T>::value>;
7911
7912// Member-template getAs<specific type>'.
7913template <typename T> const T *Type::getAs() const {
7914 static_assert(!TypeIsArrayType<T>::value,
7915 "ArrayType cannot be used with getAs!");
7916
7917 // If this is directly a T type, return it.
7918 if (const auto *Ty = dyn_cast<T>(this))
7919 return Ty;
7920
7921 // If the canonical form of this type isn't the right kind, reject it.
7922 if (!isa<T>(CanonicalType))
7923 return nullptr;
7924
7925 // If this is a typedef for the type, strip the typedef off without
7926 // losing all typedef information.
7927 return cast<T>(getUnqualifiedDesugaredType());
7928}
7929
7930template <typename T> const T *Type::getAsAdjusted() const {
7931 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7932
7933 // If this is directly a T type, return it.
7934 if (const auto *Ty = dyn_cast<T>(this))
7935 return Ty;
7936
7937 // If the canonical form of this type isn't the right kind, reject it.
7938 if (!isa<T>(CanonicalType))
7939 return nullptr;
7940
7941 // Strip off type adjustments that do not modify the underlying nature of the
7942 // type.
7943 const Type *Ty = this;
7944 while (Ty) {
7945 if (const auto *A = dyn_cast<AttributedType>(Ty))
7946 Ty = A->getModifiedType().getTypePtr();
7947 else if (const auto *A = dyn_cast<BTFTagAttributedType>(Ty))
7948 Ty = A->getWrappedType().getTypePtr();
7949 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7950 Ty = E->desugar().getTypePtr();
7951 else if (const auto *P = dyn_cast<ParenType>(Ty))
7952 Ty = P->desugar().getTypePtr();
7953 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7954 Ty = A->desugar().getTypePtr();
7955 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7956 Ty = M->desugar().getTypePtr();
7957 else
7958 break;
7959 }
7960
7961 // Just because the canonical type is correct does not mean we can use cast<>,
7962 // since we may not have stripped off all the sugar down to the base type.
7963 return dyn_cast<T>(Ty);
7964}
7965
7966inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7967 // If this is directly an array type, return it.
7968 if (const auto *arr = dyn_cast<ArrayType>(this))
7969 return arr;
7970
7971 // If the canonical form of this type isn't the right kind, reject it.
7972 if (!isa<ArrayType>(CanonicalType))
7973 return nullptr;
7974
7975 // If this is a typedef for the type, strip the typedef off without
7976 // losing all typedef information.
7977 return cast<ArrayType>(getUnqualifiedDesugaredType());
7978}
7979
7980template <typename T> const T *Type::castAs() const {
7981 static_assert(!TypeIsArrayType<T>::value,
7982 "ArrayType cannot be used with castAs!");
7983
7984 if (const auto *ty = dyn_cast<T>(this)) return ty;
7985 assert(isa<T>(CanonicalType));
7986 return cast<T>(getUnqualifiedDesugaredType());
7987}
7988
7989inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7990 assert(isa<ArrayType>(CanonicalType));
7991 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7992 return cast<ArrayType>(getUnqualifiedDesugaredType());
7993}
7994
7995DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7996 QualType CanonicalPtr)
7997 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7998#ifndef NDEBUG
7999 QualType Adjusted = getAdjustedType();
8000 (void)AttributedType::stripOuterNullability(Adjusted);
8001 assert(isa<PointerType>(Adjusted));
8002#endif
8003}
8004
8005QualType DecayedType::getPointeeType() const {
8006 QualType Decayed = getDecayedType();
8007 (void)AttributedType::stripOuterNullability(Decayed);
8008 return cast<PointerType>(Decayed)->getPointeeType();
8009}
8010
8011// Get the decimal string representation of a fixed point type, represented
8012// as a scaled integer.
8013// TODO: At some point, we should change the arguments to instead just accept an
8014// APFixedPoint instead of APSInt and scale.
8015void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
8016 unsigned Scale);
8017
8018} // namespace clang
8019
8020#endif // LLVM_CLANG_AST_TYPE_H
8021

source code of clang/include/clang/AST/Type.h