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/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
68 TypeAlignmentInBits = 4,
69 TypeAlignment = 1 << TypeAlignmentInBits
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
82 struct PointerLikeTypeTraits;
83 template<>
84 struct PointerLikeTypeTraits< ::clang::Type*> {
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
95 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132
133using CanQualType = CanQual<Type>;
134
135// Provide forward declarations for all of the *Type classes.
136#define TYPE(Class, Base) class Class##Type;
137#include "clang/AST/TypeNodes.inc"
138
139/// The collection of all-type qualifiers we support.
140/// Clang supports five independent qualifiers:
141/// * C99: const, volatile, and restrict
142/// * MS: __unaligned
143/// * Embedded C (TR18037): address spaces
144/// * Objective C: the GC attributes (none, weak, or strong)
145class Qualifiers {
146public:
147 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148 Const = 0x1,
149 Restrict = 0x2,
150 Volatile = 0x4,
151 CVRMask = Const | Volatile | Restrict
152 };
153
154 enum GC {
155 GCNone = 0,
156 Weak,
157 Strong
158 };
159
160 enum ObjCLifetime {
161 /// There is no lifetime qualification on this type.
162 OCL_None,
163
164 /// This object can be modified without requiring retains or
165 /// releases.
166 OCL_ExplicitNone,
167
168 /// Assigning into this object requires the old value to be
169 /// released and the new value to be retained. The timing of the
170 /// release of the old value is inexact: it may be moved to
171 /// immediately after the last known point where the value is
172 /// live.
173 OCL_Strong,
174
175 /// Reading or writing from this object requires a barrier call.
176 OCL_Weak,
177
178 /// Assigning into this object requires a lifetime extension.
179 OCL_Autoreleasing
180 };
181
182 enum {
183 /// The maximum supported address space number.
184 /// 23 bits should be enough for anyone.
185 MaxAddressSpace = 0x7fffffu,
186
187 /// The width of the "fast" qualifier mask.
188 FastWidth = 3,
189
190 /// The fast qualifier mask.
191 FastMask = (1 << FastWidth) - 1
192 };
193
194 /// Returns the common set of qualifiers while removing them from
195 /// the given sets.
196 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197 // If both are only CVR-qualified, bit operations are sufficient.
198 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199 Qualifiers Q;
200 Q.Mask = L.Mask & R.Mask;
201 L.Mask &= ~Q.Mask;
202 R.Mask &= ~Q.Mask;
203 return Q;
204 }
205
206 Qualifiers Q;
207 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208 Q.addCVRQualifiers(CommonCRV);
209 L.removeCVRQualifiers(CommonCRV);
210 R.removeCVRQualifiers(CommonCRV);
211
212 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213 Q.setObjCGCAttr(L.getObjCGCAttr());
214 L.removeObjCGCAttr();
215 R.removeObjCGCAttr();
216 }
217
218 if (L.getObjCLifetime() == R.getObjCLifetime()) {
219 Q.setObjCLifetime(L.getObjCLifetime());
220 L.removeObjCLifetime();
221 R.removeObjCLifetime();
222 }
223
224 if (L.getAddressSpace() == R.getAddressSpace()) {
225 Q.setAddressSpace(L.getAddressSpace());
226 L.removeAddressSpace();
227 R.removeAddressSpace();
228 }
229 return Q;
230 }
231
232 static Qualifiers fromFastMask(unsigned Mask) {
233 Qualifiers Qs;
234 Qs.addFastQualifiers(Mask);
235 return Qs;
236 }
237
238 static Qualifiers fromCVRMask(unsigned CVR) {
239 Qualifiers Qs;
240 Qs.addCVRQualifiers(CVR);
241 return Qs;
242 }
243
244 static Qualifiers fromCVRUMask(unsigned CVRU) {
245 Qualifiers Qs;
246 Qs.addCVRUQualifiers(CVRU);
247 return Qs;
248 }
249
250 // Deserialize qualifiers from an opaque representation.
251 static Qualifiers fromOpaqueValue(unsigned opaque) {
252 Qualifiers Qs;
253 Qs.Mask = opaque;
254 return Qs;
255 }
256
257 // Serialize these qualifiers into an opaque representation.
258 unsigned getAsOpaqueValue() const {
259 return Mask;
260 }
261
262 bool hasConst() const { return Mask & Const; }
263 bool hasOnlyConst() const { return Mask == Const; }
264 void removeConst() { Mask &= ~Const; }
265 void addConst() { Mask |= Const; }
266
267 bool hasVolatile() const { return Mask & Volatile; }
268 bool hasOnlyVolatile() const { return Mask == Volatile; }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 bool hasOnlyRestrict() const { return Mask == Restrict; }
274 void removeRestrict() { Mask &= ~Restrict; }
275 void addRestrict() { Mask |= Restrict; }
276
277 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type);
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328 Qualifiers withoutAddressSpace() const {
329 Qualifiers qs = *this;
330 qs.removeAddressSpace();
331 return qs;
332 }
333
334 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335 ObjCLifetime getObjCLifetime() const {
336 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337 }
338 void setObjCLifetime(ObjCLifetime type) {
339 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340 }
341 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342 void addObjCLifetime(ObjCLifetime type) {
343 assert(type);
344 assert(!hasObjCLifetime());
345 Mask |= (type << LifetimeShift);
346 }
347
348 /// True if the lifetime is neither None or ExplicitNone.
349 bool hasNonTrivialObjCLifetime() const {
350 ObjCLifetime lifetime = getObjCLifetime();
351 return (lifetime > OCL_ExplicitNone);
352 }
353
354 /// True if the lifetime is either strong or weak.
355 bool hasStrongOrWeakObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358 }
359
360 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361 LangAS getAddressSpace() const {
362 return static_cast<LangAS>(Mask >> AddressSpaceShift);
363 }
364 bool hasTargetSpecificAddressSpace() const {
365 return isTargetAddressSpace(getAddressSpace());
366 }
367 /// Get the address space attribute value to be printed by diagnostics.
368 unsigned getAddressSpaceAttributePrintValue() const {
369 auto Addr = getAddressSpace();
370 // This function is not supposed to be used with language specific
371 // address spaces. If that happens, the diagnostic message should consider
372 // printing the QualType instead of the address space value.
373 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
374 if (Addr != LangAS::Default)
375 return toTargetAddressSpace(Addr);
376 // TODO: The diagnostic messages where Addr may be 0 should be fixed
377 // since it cannot differentiate the situation where 0 denotes the default
378 // address space or user specified __attribute__((address_space(0))).
379 return 0;
380 }
381 void setAddressSpace(LangAS space) {
382 assert((unsigned)space <= MaxAddressSpace);
383 Mask = (Mask & ~AddressSpaceMask)
384 | (((uint32_t) space) << AddressSpaceShift);
385 }
386 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387 void addAddressSpace(LangAS space) {
388 assert(space != LangAS::Default);
389 setAddressSpace(space);
390 }
391
392 // Fast qualifiers are those that can be allocated directly
393 // on a QualType object.
394 bool hasFastQualifiers() const { return getFastQualifiers(); }
395 unsigned getFastQualifiers() const { return Mask & FastMask; }
396 void setFastQualifiers(unsigned mask) {
397 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
398 Mask = (Mask & ~FastMask) | mask;
399 }
400 void removeFastQualifiers(unsigned mask) {
401 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
402 Mask &= ~mask;
403 }
404 void removeFastQualifiers() {
405 removeFastQualifiers(FastMask);
406 }
407 void addFastQualifiers(unsigned mask) {
408 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
409 Mask |= mask;
410 }
411
412 /// Return true if the set contains any qualifiers which require an ExtQuals
413 /// node to be allocated.
414 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415 Qualifiers getNonFastQualifiers() const {
416 Qualifiers Quals = *this;
417 Quals.setFastQualifiers(0);
418 return Quals;
419 }
420
421 /// Return true if the set contains any qualifiers.
422 bool hasQualifiers() const { return Mask; }
423 bool empty() const { return !Mask; }
424
425 /// Add the qualifiers from the given set to this set.
426 void addQualifiers(Qualifiers Q) {
427 // If the other set doesn't have any non-boolean qualifiers, just
428 // bit-or it in.
429 if (!(Q.Mask & ~CVRMask))
430 Mask |= Q.Mask;
431 else {
432 Mask |= (Q.Mask & CVRMask);
433 if (Q.hasAddressSpace())
434 addAddressSpace(Q.getAddressSpace());
435 if (Q.hasObjCGCAttr())
436 addObjCGCAttr(Q.getObjCGCAttr());
437 if (Q.hasObjCLifetime())
438 addObjCLifetime(Q.getObjCLifetime());
439 }
440 }
441
442 /// Remove the qualifiers from the given set from this set.
443 void removeQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-and the inverse in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask &= ~Q.Mask;
448 else {
449 Mask &= ~(Q.Mask & CVRMask);
450 if (getObjCGCAttr() == Q.getObjCGCAttr())
451 removeObjCGCAttr();
452 if (getObjCLifetime() == Q.getObjCLifetime())
453 removeObjCLifetime();
454 if (getAddressSpace() == Q.getAddressSpace())
455 removeAddressSpace();
456 }
457 }
458
459 /// Add the qualifiers from the given set to this set, given that
460 /// they don't conflict.
461 void addConsistentQualifiers(Qualifiers qs) {
462 assert(getAddressSpace() == qs.getAddressSpace() ||
463 !hasAddressSpace() || !qs.hasAddressSpace());
464 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
465 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
466 assert(getObjCLifetime() == qs.getObjCLifetime() ||
467 !hasObjCLifetime() || !qs.hasObjCLifetime());
468 Mask |= qs.Mask;
469 }
470
471 /// Returns true if address space A is equal to or a superset of B.
472 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473 /// overlapping address spaces.
474 /// CL1.1 or CL1.2:
475 /// every address space is a superset of itself.
476 /// CL2.0 adds:
477 /// __generic is a superset of any address space except for __constant.
478 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479 // Address spaces must match exactly.
480 return A == B ||
481 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482 // for __constant can be used as __generic.
483 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
484 // We also define global_device and global_host address spaces,
485 // to distinguish global pointers allocated on host from pointers
486 // allocated on device, which are a subset of __global.
487 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
488 B == LangAS::opencl_global_host)) ||
489 // Consider pointer size address spaces to be equivalent to default.
490 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
491 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
492 // Default is a superset of SYCL address spaces.
493 (A == LangAS::Default &&
494 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
495 B == LangAS::sycl_global));
496 }
497
498 /// Returns true if the address space in these qualifiers is equal to or
499 /// a superset of the address space in the argument qualifiers.
500 bool isAddressSpaceSupersetOf(Qualifiers other) const {
501 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
502 }
503
504 /// Determines if these qualifiers compatibly include another set.
505 /// Generally this answers the question of whether an object with the other
506 /// qualifiers can be safely used as an object with these qualifiers.
507 bool compatiblyIncludes(Qualifiers other) const {
508 return isAddressSpaceSupersetOf(other) &&
509 // ObjC GC qualifiers can match, be added, or be removed, but can't
510 // be changed.
511 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
512 !other.hasObjCGCAttr()) &&
513 // ObjC lifetime qualifiers must match exactly.
514 getObjCLifetime() == other.getObjCLifetime() &&
515 // CVR qualifiers may subset.
516 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
517 // U qualifier may superset.
518 (!other.hasUnaligned() || hasUnaligned());
519 }
520
521 /// Determines if these qualifiers compatibly include another set of
522 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
523 ///
524 /// One set of Objective-C lifetime qualifiers compatibly includes the other
525 /// if the lifetime qualifiers match, or if both are non-__weak and the
526 /// including set also contains the 'const' qualifier, or both are non-__weak
527 /// and one is None (which can only happen in non-ARC modes).
528 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
529 if (getObjCLifetime() == other.getObjCLifetime())
530 return true;
531
532 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
533 return false;
534
535 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
536 return true;
537
538 return hasConst();
539 }
540
541 /// Determine whether this set of qualifiers is a strict superset of
542 /// another set of qualifiers, not considering qualifier compatibility.
543 bool isStrictSupersetOf(Qualifiers Other) const;
544
545 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
546 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
547
548 explicit operator bool() const { return hasQualifiers(); }
549
550 Qualifiers &operator+=(Qualifiers R) {
551 addQualifiers(R);
552 return *this;
553 }
554
555 // Union two qualifier sets. If an enumerated qualifier appears
556 // in both sets, use the one from the right.
557 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
558 L += R;
559 return L;
560 }
561
562 Qualifiers &operator-=(Qualifiers R) {
563 removeQualifiers(R);
564 return *this;
565 }
566
567 /// Compute the difference between two qualifier sets.
568 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
569 L -= R;
570 return L;
571 }
572
573 std::string getAsString() const;
574 std::string getAsString(const PrintingPolicy &Policy) const;
575
576 static std::string getAddrSpaceAsString(LangAS AS);
577
578 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
579 void print(raw_ostream &OS, const PrintingPolicy &Policy,
580 bool appendSpaceIfNonEmpty = false) const;
581
582 void Profile(llvm::FoldingSetNodeID &ID) const {
583 ID.AddInteger(Mask);
584 }
585
586private:
587 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
588 // |C R V|U|GCAttr|Lifetime|AddressSpace|
589 uint32_t Mask = 0;
590
591 static const uint32_t UMask = 0x8;
592 static const uint32_t UShift = 3;
593 static const uint32_t GCAttrMask = 0x30;
594 static const uint32_t GCAttrShift = 4;
595 static const uint32_t LifetimeMask = 0x1C0;
596 static const uint32_t LifetimeShift = 6;
597 static const uint32_t AddressSpaceMask =
598 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
599 static const uint32_t AddressSpaceShift = 9;
600};
601
602/// A std::pair-like structure for storing a qualified type split
603/// into its local qualifiers and its locally-unqualified type.
604struct SplitQualType {
605 /// The locally-unqualified type.
606 const Type *Ty = nullptr;
607
608 /// The local qualifiers.
609 Qualifiers Quals;
610
611 SplitQualType() = default;
612 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
613
614 SplitQualType getSingleStepDesugaredType() const; // end of this file
615
616 // Make std::tie work.
617 std::pair<const Type *,Qualifiers> asPair() const {
618 return std::pair<const Type *, Qualifiers>(Ty, Quals);
619 }
620
621 friend bool operator==(SplitQualType a, SplitQualType b) {
622 return a.Ty == b.Ty && a.Quals == b.Quals;
623 }
624 friend bool operator!=(SplitQualType a, SplitQualType b) {
625 return a.Ty != b.Ty || a.Quals != b.Quals;
626 }
627};
628
629/// The kind of type we are substituting Objective-C type arguments into.
630///
631/// The kind of substitution affects the replacement of type parameters when
632/// no concrete type information is provided, e.g., when dealing with an
633/// unspecialized type.
634enum class ObjCSubstitutionContext {
635 /// An ordinary type.
636 Ordinary,
637
638 /// The result type of a method or function.
639 Result,
640
641 /// The parameter type of a method or function.
642 Parameter,
643
644 /// The type of a property.
645 Property,
646
647 /// The superclass of a type.
648 Superclass,
649};
650
651/// A (possibly-)qualified type.
652///
653/// For efficiency, we don't store CV-qualified types as nodes on their
654/// own: instead each reference to a type stores the qualifiers. This
655/// greatly reduces the number of nodes we need to allocate for types (for
656/// example we only need one for 'int', 'const int', 'volatile int',
657/// 'const volatile int', etc).
658///
659/// As an added efficiency bonus, instead of making this a pair, we
660/// just store the two bits we care about in the low bits of the
661/// pointer. To handle the packing/unpacking, we make QualType be a
662/// simple wrapper class that acts like a smart pointer. A third bit
663/// indicates whether there are extended qualifiers present, in which
664/// case the pointer points to a special structure.
665class QualType {
666 friend class QualifierCollector;
667
668 // Thankfully, these are efficiently composable.
669 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
670 Qualifiers::FastWidth> Value;
671
672 const ExtQuals *getExtQualsUnsafe() const {
673 return Value.getPointer().get<const ExtQuals*>();
674 }
675
676 const Type *getTypePtrUnsafe() const {
677 return Value.getPointer().get<const Type*>();
678 }
679
680 const ExtQualsTypeCommonBase *getCommonPtr() const {
681 assert(!isNull() && "Cannot retrieve a NULL type pointer");
682 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
683 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
684 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
685 }
686
687public:
688 QualType() = default;
689 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
690 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
691
692 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
693 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
694
695 /// Retrieves a pointer to the underlying (unqualified) type.
696 ///
697 /// This function requires that the type not be NULL. If the type might be
698 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
699 const Type *getTypePtr() const;
700
701 const Type *getTypePtrOrNull() const;
702
703 /// Retrieves a pointer to the name of the base type.
704 const IdentifierInfo *getBaseTypeIdentifier() const;
705
706 /// Divides a QualType into its unqualified type and a set of local
707 /// qualifiers.
708 SplitQualType split() const;
709
710 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
711
712 static QualType getFromOpaquePtr(const void *Ptr) {
713 QualType T;
714 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
715 return T;
716 }
717
718 const Type &operator*() const {
719 return *getTypePtr();
720 }
721
722 const Type *operator->() const {
723 return getTypePtr();
724 }
725
726 bool isCanonical() const;
727 bool isCanonicalAsParam() const;
728
729 /// Return true if this QualType doesn't point to a type yet.
730 bool isNull() const {
731 return Value.getPointer().isNull();
732 }
733
734 /// Determine whether this particular QualType instance has the
735 /// "const" qualifier set, without looking through typedefs that may have
736 /// added "const" at a different level.
737 bool isLocalConstQualified() const {
738 return (getLocalFastQualifiers() & Qualifiers::Const);
739 }
740
741 /// Determine whether this type is const-qualified.
742 bool isConstQualified() const;
743
744 /// Determine whether this particular QualType instance has the
745 /// "restrict" qualifier set, without looking through typedefs that may have
746 /// added "restrict" at a different level.
747 bool isLocalRestrictQualified() const {
748 return (getLocalFastQualifiers() & Qualifiers::Restrict);
749 }
750
751 /// Determine whether this type is restrict-qualified.
752 bool isRestrictQualified() const;
753
754 /// Determine whether this particular QualType instance has the
755 /// "volatile" qualifier set, without looking through typedefs that may have
756 /// added "volatile" at a different level.
757 bool isLocalVolatileQualified() const {
758 return (getLocalFastQualifiers() & Qualifiers::Volatile);
759 }
760
761 /// Determine whether this type is volatile-qualified.
762 bool isVolatileQualified() const;
763
764 /// Determine whether this particular QualType instance has any
765 /// qualifiers, without looking through any typedefs that might add
766 /// qualifiers at a different level.
767 bool hasLocalQualifiers() const {
768 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
769 }
770
771 /// Determine whether this type has any qualifiers.
772 bool hasQualifiers() const;
773
774 /// Determine whether this particular QualType instance has any
775 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
776 /// instance.
777 bool hasLocalNonFastQualifiers() const {
778 return Value.getPointer().is<const ExtQuals*>();
779 }
780
781 /// Retrieve the set of qualifiers local to this particular QualType
782 /// instance, not including any qualifiers acquired through typedefs or
783 /// other sugar.
784 Qualifiers getLocalQualifiers() const;
785
786 /// Retrieve the set of qualifiers applied to this type.
787 Qualifiers getQualifiers() const;
788
789 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
790 /// local to this particular QualType instance, not including any qualifiers
791 /// acquired through typedefs or other sugar.
792 unsigned getLocalCVRQualifiers() const {
793 return getLocalFastQualifiers();
794 }
795
796 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
797 /// applied to this type.
798 unsigned getCVRQualifiers() const;
799
800 bool isConstant(const ASTContext& Ctx) const {
801 return QualType::isConstant(*this, Ctx);
802 }
803
804 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
805 bool isPODType(const ASTContext &Context) const;
806
807 /// Return true if this is a POD type according to the rules of the C++98
808 /// standard, regardless of the current compilation's language.
809 bool isCXX98PODType(const ASTContext &Context) const;
810
811 /// Return true if this is a POD type according to the more relaxed rules
812 /// of the C++11 standard, regardless of the current compilation's language.
813 /// (C++0x [basic.types]p9). Note that, unlike
814 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
815 bool isCXX11PODType(const ASTContext &Context) const;
816
817 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
818 bool isTrivialType(const ASTContext &Context) const;
819
820 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
821 bool isTriviallyCopyableType(const ASTContext &Context) const;
822
823
824 /// Returns true if it is a class and it might be dynamic.
825 bool mayBeDynamicClass() const;
826
827 /// Returns true if it is not a class or if the class might not be dynamic.
828 bool mayBeNotDynamicClass() const;
829
830 // Don't promise in the API that anything besides 'const' can be
831 // easily added.
832
833 /// Add the `const` type qualifier to this QualType.
834 void addConst() {
835 addFastQualifiers(Qualifiers::Const);
836 }
837 QualType withConst() const {
838 return withFastQualifiers(Qualifiers::Const);
839 }
840
841 /// Add the `volatile` type qualifier to this QualType.
842 void addVolatile() {
843 addFastQualifiers(Qualifiers::Volatile);
844 }
845 QualType withVolatile() const {
846 return withFastQualifiers(Qualifiers::Volatile);
847 }
848
849 /// Add the `restrict` qualifier to this QualType.
850 void addRestrict() {
851 addFastQualifiers(Qualifiers::Restrict);
852 }
853 QualType withRestrict() const {
854 return withFastQualifiers(Qualifiers::Restrict);
855 }
856
857 QualType withCVRQualifiers(unsigned CVR) const {
858 return withFastQualifiers(CVR);
859 }
860
861 void addFastQualifiers(unsigned TQs) {
862 assert(!(TQs & ~Qualifiers::FastMask)
863 && "non-fast qualifier bits set in mask!");
864 Value.setInt(Value.getInt() | TQs);
865 }
866
867 void removeLocalConst();
868 void removeLocalVolatile();
869 void removeLocalRestrict();
870 void removeLocalCVRQualifiers(unsigned Mask);
871
872 void removeLocalFastQualifiers() { Value.setInt(0); }
873 void removeLocalFastQualifiers(unsigned Mask) {
874 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
875 Value.setInt(Value.getInt() & ~Mask);
876 }
877
878 // Creates a type with the given qualifiers in addition to any
879 // qualifiers already on this type.
880 QualType withFastQualifiers(unsigned TQs) const {
881 QualType T = *this;
882 T.addFastQualifiers(TQs);
883 return T;
884 }
885
886 // Creates a type with exactly the given fast qualifiers, removing
887 // any existing fast qualifiers.
888 QualType withExactLocalFastQualifiers(unsigned TQs) const {
889 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
890 }
891
892 // Removes fast qualifiers, but leaves any extended qualifiers in place.
893 QualType withoutLocalFastQualifiers() const {
894 QualType T = *this;
895 T.removeLocalFastQualifiers();
896 return T;
897 }
898
899 QualType getCanonicalType() const;
900
901 /// Return this type with all of the instance-specific qualifiers
902 /// removed, but without removing any qualifiers that may have been applied
903 /// through typedefs.
904 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
905
906 /// Retrieve the unqualified variant of the given type,
907 /// removing as little sugar as possible.
908 ///
909 /// This routine looks through various kinds of sugar to find the
910 /// least-desugared type that is unqualified. For example, given:
911 ///
912 /// \code
913 /// typedef int Integer;
914 /// typedef const Integer CInteger;
915 /// typedef CInteger DifferenceType;
916 /// \endcode
917 ///
918 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
919 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
920 ///
921 /// The resulting type might still be qualified if it's sugar for an array
922 /// type. To strip qualifiers even from within a sugared array type, use
923 /// ASTContext::getUnqualifiedArrayType.
924 inline QualType getUnqualifiedType() const;
925
926 /// Retrieve the unqualified variant of the given type, removing as little
927 /// sugar as possible.
928 ///
929 /// Like getUnqualifiedType(), but also returns the set of
930 /// qualifiers that were built up.
931 ///
932 /// The resulting type might still be qualified if it's sugar for an array
933 /// type. To strip qualifiers even from within a sugared array type, use
934 /// ASTContext::getUnqualifiedArrayType.
935 inline SplitQualType getSplitUnqualifiedType() const;
936
937 /// Determine whether this type is more qualified than the other
938 /// given type, requiring exact equality for non-CVR qualifiers.
939 bool isMoreQualifiedThan(QualType Other) const;
940
941 /// Determine whether this type is at least as qualified as the other
942 /// given type, requiring exact equality for non-CVR qualifiers.
943 bool isAtLeastAsQualifiedAs(QualType Other) const;
944
945 QualType getNonReferenceType() const;
946
947 /// Determine the type of a (typically non-lvalue) expression with the
948 /// specified result type.
949 ///
950 /// This routine should be used for expressions for which the return type is
951 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
952 /// an lvalue. It removes a top-level reference (since there are no
953 /// expressions of reference type) and deletes top-level cvr-qualifiers
954 /// from non-class types (in C++) or all types (in C).
955 QualType getNonLValueExprType(const ASTContext &Context) const;
956
957 /// Remove an outer pack expansion type (if any) from this type. Used as part
958 /// of converting the type of a declaration to the type of an expression that
959 /// references that expression. It's meaningless for an expression to have a
960 /// pack expansion type.
961 QualType getNonPackExpansionType() const;
962
963 /// Return the specified type with any "sugar" removed from
964 /// the type. This takes off typedefs, typeof's etc. If the outer level of
965 /// the type is already concrete, it returns it unmodified. This is similar
966 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
967 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
968 /// concrete.
969 ///
970 /// Qualifiers are left in place.
971 QualType getDesugaredType(const ASTContext &Context) const {
972 return getDesugaredType(*this, Context);
973 }
974
975 SplitQualType getSplitDesugaredType() const {
976 return getSplitDesugaredType(*this);
977 }
978
979 /// Return the specified type with one level of "sugar" removed from
980 /// the type.
981 ///
982 /// This routine takes off the first typedef, typeof, etc. If the outer level
983 /// of the type is already concrete, it returns it unmodified.
984 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
985 return getSingleStepDesugaredTypeImpl(*this, Context);
986 }
987
988 /// Returns the specified type after dropping any
989 /// outer-level parentheses.
990 QualType IgnoreParens() const {
991 if (isa<ParenType>(*this))
992 return QualType::IgnoreParens(*this);
993 return *this;
994 }
995
996 /// Indicate whether the specified types and qualifiers are identical.
997 friend bool operator==(const QualType &LHS, const QualType &RHS) {
998 return LHS.Value == RHS.Value;
999 }
1000 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1001 return LHS.Value != RHS.Value;
1002 }
1003 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1004 return LHS.Value < RHS.Value;
1005 }
1006
1007 static std::string getAsString(SplitQualType split,
1008 const PrintingPolicy &Policy) {
1009 return getAsString(split.Ty, split.Quals, Policy);
1010 }
1011 static std::string getAsString(const Type *ty, Qualifiers qs,
1012 const PrintingPolicy &Policy);
1013
1014 std::string getAsString() const;
1015 std::string getAsString(const PrintingPolicy &Policy) const;
1016
1017 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1018 const Twine &PlaceHolder = Twine(),
1019 unsigned Indentation = 0) const;
1020
1021 static void print(SplitQualType split, raw_ostream &OS,
1022 const PrintingPolicy &policy, const Twine &PlaceHolder,
1023 unsigned Indentation = 0) {
1024 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1025 }
1026
1027 static void print(const Type *ty, Qualifiers qs,
1028 raw_ostream &OS, const PrintingPolicy &policy,
1029 const Twine &PlaceHolder,
1030 unsigned Indentation = 0);
1031
1032 void getAsStringInternal(std::string &Str,
1033 const PrintingPolicy &Policy) const;
1034
1035 static void getAsStringInternal(SplitQualType split, std::string &out,
1036 const PrintingPolicy &policy) {
1037 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1038 }
1039
1040 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1041 std::string &out,
1042 const PrintingPolicy &policy);
1043
1044 class StreamedQualTypeHelper {
1045 const QualType &T;
1046 const PrintingPolicy &Policy;
1047 const Twine &PlaceHolder;
1048 unsigned Indentation;
1049
1050 public:
1051 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1052 const Twine &PlaceHolder, unsigned Indentation)
1053 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1054 Indentation(Indentation) {}
1055
1056 friend raw_ostream &operator<<(raw_ostream &OS,
1057 const StreamedQualTypeHelper &SQT) {
1058 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1059 return OS;
1060 }
1061 };
1062
1063 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1064 const Twine &PlaceHolder = Twine(),
1065 unsigned Indentation = 0) const {
1066 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1067 }
1068
1069 void dump(const char *s) const;
1070 void dump() const;
1071 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1072
1073 void Profile(llvm::FoldingSetNodeID &ID) const {
1074 ID.AddPointer(getAsOpaquePtr());
1075 }
1076
1077 /// Check if this type has any address space qualifier.
1078 inline bool hasAddressSpace() const;
1079
1080 /// Return the address space of this type.
1081 inline LangAS getAddressSpace() const;
1082
1083 /// Returns true if address space qualifiers overlap with T address space
1084 /// qualifiers.
1085 /// OpenCL C defines conversion rules for pointers to different address spaces
1086 /// and notion of overlapping address spaces.
1087 /// CL1.1 or CL1.2:
1088 /// address spaces overlap iff they are they same.
1089 /// OpenCL C v2.0 s6.5.5 adds:
1090 /// __generic overlaps with any address space except for __constant.
1091 bool isAddressSpaceOverlapping(QualType T) const {
1092 Qualifiers Q = getQualifiers();
1093 Qualifiers TQ = T.getQualifiers();
1094 // Address spaces overlap if at least one of them is a superset of another
1095 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1096 }
1097
1098 /// Returns gc attribute of this type.
1099 inline Qualifiers::GC getObjCGCAttr() const;
1100
1101 /// true when Type is objc's weak.
1102 bool isObjCGCWeak() const {
1103 return getObjCGCAttr() == Qualifiers::Weak;
1104 }
1105
1106 /// true when Type is objc's strong.
1107 bool isObjCGCStrong() const {
1108 return getObjCGCAttr() == Qualifiers::Strong;
1109 }
1110
1111 /// Returns lifetime attribute of this type.
1112 Qualifiers::ObjCLifetime getObjCLifetime() const {
1113 return getQualifiers().getObjCLifetime();
1114 }
1115
1116 bool hasNonTrivialObjCLifetime() const {
1117 return getQualifiers().hasNonTrivialObjCLifetime();
1118 }
1119
1120 bool hasStrongOrWeakObjCLifetime() const {
1121 return getQualifiers().hasStrongOrWeakObjCLifetime();
1122 }
1123
1124 // true when Type is objc's weak and weak is enabled but ARC isn't.
1125 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1126
1127 enum PrimitiveDefaultInitializeKind {
1128 /// The type does not fall into any of the following categories. Note that
1129 /// this case is zero-valued so that values of this enum can be used as a
1130 /// boolean condition for non-triviality.
1131 PDIK_Trivial,
1132
1133 /// The type is an Objective-C retainable pointer type that is qualified
1134 /// with the ARC __strong qualifier.
1135 PDIK_ARCStrong,
1136
1137 /// The type is an Objective-C retainable pointer type that is qualified
1138 /// with the ARC __weak qualifier.
1139 PDIK_ARCWeak,
1140
1141 /// The type is a struct containing a field whose type is not PCK_Trivial.
1142 PDIK_Struct
1143 };
1144
1145 /// Functions to query basic properties of non-trivial C struct types.
1146
1147 /// Check if this is a non-trivial type that would cause a C struct
1148 /// transitively containing this type to be non-trivial to default initialize
1149 /// and return the kind.
1150 PrimitiveDefaultInitializeKind
1151 isNonTrivialToPrimitiveDefaultInitialize() const;
1152
1153 enum PrimitiveCopyKind {
1154 /// The type does not fall into any of the following categories. Note that
1155 /// this case is zero-valued so that values of this enum can be used as a
1156 /// boolean condition for non-triviality.
1157 PCK_Trivial,
1158
1159 /// The type would be trivial except that it is volatile-qualified. Types
1160 /// that fall into one of the other non-trivial cases may additionally be
1161 /// volatile-qualified.
1162 PCK_VolatileTrivial,
1163
1164 /// The type is an Objective-C retainable pointer type that is qualified
1165 /// with the ARC __strong qualifier.
1166 PCK_ARCStrong,
1167
1168 /// The type is an Objective-C retainable pointer type that is qualified
1169 /// with the ARC __weak qualifier.
1170 PCK_ARCWeak,
1171
1172 /// The type is a struct containing a field whose type is neither
1173 /// PCK_Trivial nor PCK_VolatileTrivial.
1174 /// Note that a C++ struct type does not necessarily match this; C++ copying
1175 /// semantics are too complex to express here, in part because they depend
1176 /// on the exact constructor or assignment operator that is chosen by
1177 /// overload resolution to do the copy.
1178 PCK_Struct
1179 };
1180
1181 /// Check if this is a non-trivial type that would cause a C struct
1182 /// transitively containing this type to be non-trivial to copy and return the
1183 /// kind.
1184 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1185
1186 /// Check if this is a non-trivial type that would cause a C struct
1187 /// transitively containing this type to be non-trivial to destructively
1188 /// move and return the kind. Destructive move in this context is a C++-style
1189 /// move in which the source object is placed in a valid but unspecified state
1190 /// after it is moved, as opposed to a truly destructive move in which the
1191 /// source object is placed in an uninitialized state.
1192 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1193
1194 enum DestructionKind {
1195 DK_none,
1196 DK_cxx_destructor,
1197 DK_objc_strong_lifetime,
1198 DK_objc_weak_lifetime,
1199 DK_nontrivial_c_struct
1200 };
1201
1202 /// Returns a nonzero value if objects of this type require
1203 /// non-trivial work to clean up after. Non-zero because it's
1204 /// conceivable that qualifiers (objc_gc(weak)?) could make
1205 /// something require destruction.
1206 DestructionKind isDestructedType() const {
1207 return isDestructedTypeImpl(*this);
1208 }
1209
1210 /// Check if this is or contains a C union that is non-trivial to
1211 /// default-initialize, which is a union that has a member that is non-trivial
1212 /// to default-initialize. If this returns true,
1213 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1214 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1215
1216 /// Check if this is or contains a C union that is non-trivial to destruct,
1217 /// which is a union that has a member that is non-trivial to destruct. If
1218 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1219 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1220
1221 /// Check if this is or contains a C union that is non-trivial to copy, which
1222 /// is a union that has a member that is non-trivial to copy. If this returns
1223 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1224 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1225
1226 /// Determine whether expressions of the given type are forbidden
1227 /// from being lvalues in C.
1228 ///
1229 /// The expression types that are forbidden to be lvalues are:
1230 /// - 'void', but not qualified void
1231 /// - function types
1232 ///
1233 /// The exact rule here is C99 6.3.2.1:
1234 /// An lvalue is an expression with an object type or an incomplete
1235 /// type other than void.
1236 bool isCForbiddenLValueType() const;
1237
1238 /// Substitute type arguments for the Objective-C type parameters used in the
1239 /// subject type.
1240 ///
1241 /// \param ctx ASTContext in which the type exists.
1242 ///
1243 /// \param typeArgs The type arguments that will be substituted for the
1244 /// Objective-C type parameters in the subject type, which are generally
1245 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1246 /// parameters will be replaced with their bounds or id/Class, as appropriate
1247 /// for the context.
1248 ///
1249 /// \param context The context in which the subject type was written.
1250 ///
1251 /// \returns the resulting type.
1252 QualType substObjCTypeArgs(ASTContext &ctx,
1253 ArrayRef<QualType> typeArgs,
1254 ObjCSubstitutionContext context) const;
1255
1256 /// Substitute type arguments from an object type for the Objective-C type
1257 /// parameters used in the subject type.
1258 ///
1259 /// This operation combines the computation of type arguments for
1260 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1261 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1262 /// callers that need to perform a single substitution in isolation.
1263 ///
1264 /// \param objectType The type of the object whose member type we're
1265 /// substituting into. For example, this might be the receiver of a message
1266 /// or the base of a property access.
1267 ///
1268 /// \param dc The declaration context from which the subject type was
1269 /// retrieved, which indicates (for example) which type parameters should
1270 /// be substituted.
1271 ///
1272 /// \param context The context in which the subject type was written.
1273 ///
1274 /// \returns the subject type after replacing all of the Objective-C type
1275 /// parameters with their corresponding arguments.
1276 QualType substObjCMemberType(QualType objectType,
1277 const DeclContext *dc,
1278 ObjCSubstitutionContext context) const;
1279
1280 /// Strip Objective-C "__kindof" types from the given type.
1281 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1282
1283 /// Remove all qualifiers including _Atomic.
1284 QualType getAtomicUnqualifiedType() const;
1285
1286private:
1287 // These methods are implemented in a separate translation unit;
1288 // "static"-ize them to avoid creating temporary QualTypes in the
1289 // caller.
1290 static bool isConstant(QualType T, const ASTContext& Ctx);
1291 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1292 static SplitQualType getSplitDesugaredType(QualType T);
1293 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1294 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1295 const ASTContext &C);
1296 static QualType IgnoreParens(QualType T);
1297 static DestructionKind isDestructedTypeImpl(QualType type);
1298
1299 /// Check if \param RD is or contains a non-trivial C union.
1300 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1301 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1302 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1303};
1304
1305} // namespace clang
1306
1307namespace llvm {
1308
1309/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1310/// to a specific Type class.
1311template<> struct simplify_type< ::clang::QualType> {
1312 using SimpleType = const ::clang::Type *;
1313
1314 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1315 return Val.getTypePtr();
1316 }
1317};
1318
1319// Teach SmallPtrSet that QualType is "basically a pointer".
1320template<>
1321struct PointerLikeTypeTraits<clang::QualType> {
1322 static inline void *getAsVoidPointer(clang::QualType P) {
1323 return P.getAsOpaquePtr();
1324 }
1325
1326 static inline clang::QualType getFromVoidPointer(void *P) {
1327 return clang::QualType::getFromOpaquePtr(P);
1328 }
1329
1330 // Various qualifiers go in low bits.
1331 static constexpr int NumLowBitsAvailable = 0;
1332};
1333
1334} // namespace llvm
1335
1336namespace clang {
1337
1338/// Base class that is common to both the \c ExtQuals and \c Type
1339/// classes, which allows \c QualType to access the common fields between the
1340/// two.
1341class ExtQualsTypeCommonBase {
1342 friend class ExtQuals;
1343 friend class QualType;
1344 friend class Type;
1345
1346 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1347 /// a self-referential pointer (for \c Type).
1348 ///
1349 /// This pointer allows an efficient mapping from a QualType to its
1350 /// underlying type pointer.
1351 const Type *const BaseType;
1352
1353 /// The canonical type of this type. A QualType.
1354 QualType CanonicalType;
1355
1356 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1357 : BaseType(baseType), CanonicalType(canon) {}
1358};
1359
1360/// We can encode up to four bits in the low bits of a
1361/// type pointer, but there are many more type qualifiers that we want
1362/// to be able to apply to an arbitrary type. Therefore we have this
1363/// struct, intended to be heap-allocated and used by QualType to
1364/// store qualifiers.
1365///
1366/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1367/// in three low bits on the QualType pointer; a fourth bit records whether
1368/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1369/// Objective-C GC attributes) are much more rare.
1370class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1371 // NOTE: changing the fast qualifiers should be straightforward as
1372 // long as you don't make 'const' non-fast.
1373 // 1. Qualifiers:
1374 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1375 // Fast qualifiers must occupy the low-order bits.
1376 // b) Update Qualifiers::FastWidth and FastMask.
1377 // 2. QualType:
1378 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1379 // b) Update remove{Volatile,Restrict}, defined near the end of
1380 // this header.
1381 // 3. ASTContext:
1382 // a) Update get{Volatile,Restrict}Type.
1383
1384 /// The immutable set of qualifiers applied by this node. Always contains
1385 /// extended qualifiers.
1386 Qualifiers Quals;
1387
1388 ExtQuals *this_() { return this; }
1389
1390public:
1391 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1392 : ExtQualsTypeCommonBase(baseType,
1393 canon.isNull() ? QualType(this_(), 0) : canon),
1394 Quals(quals) {
1395 assert(Quals.hasNonFastQualifiers()
1396 && "ExtQuals created with no fast qualifiers");
1397 assert(!Quals.hasFastQualifiers()
1398 && "ExtQuals created with fast qualifiers");
1399 }
1400
1401 Qualifiers getQualifiers() const { return Quals; }
1402
1403 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1404 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1405
1406 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1407 Qualifiers::ObjCLifetime getObjCLifetime() const {
1408 return Quals.getObjCLifetime();
1409 }
1410
1411 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1412 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1413
1414 const Type *getBaseType() const { return BaseType; }
1415
1416public:
1417 void Profile(llvm::FoldingSetNodeID &ID) const {
1418 Profile(ID, getBaseType(), Quals);
1419 }
1420
1421 static void Profile(llvm::FoldingSetNodeID &ID,
1422 const Type *BaseType,
1423 Qualifiers Quals) {
1424 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1425 ID.AddPointer(BaseType);
1426 Quals.Profile(ID);
1427 }
1428};
1429
1430/// The kind of C++11 ref-qualifier associated with a function type.
1431/// This determines whether a member function's "this" object can be an
1432/// lvalue, rvalue, or neither.
1433enum RefQualifierKind {
1434 /// No ref-qualifier was provided.
1435 RQ_None = 0,
1436
1437 /// An lvalue ref-qualifier was provided (\c &).
1438 RQ_LValue,
1439
1440 /// An rvalue ref-qualifier was provided (\c &&).
1441 RQ_RValue
1442};
1443
1444/// Which keyword(s) were used to create an AutoType.
1445enum class AutoTypeKeyword {
1446 /// auto
1447 Auto,
1448
1449 /// decltype(auto)
1450 DecltypeAuto,
1451
1452 /// __auto_type (GNU extension)
1453 GNUAutoType
1454};
1455
1456/// The base class of the type hierarchy.
1457///
1458/// A central concept with types is that each type always has a canonical
1459/// type. A canonical type is the type with any typedef names stripped out
1460/// of it or the types it references. For example, consider:
1461///
1462/// typedef int foo;
1463/// typedef foo* bar;
1464/// 'int *' 'foo *' 'bar'
1465///
1466/// There will be a Type object created for 'int'. Since int is canonical, its
1467/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1468/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1469/// there is a PointerType that represents 'int*', which, like 'int', is
1470/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1471/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1472/// is also 'int*'.
1473///
1474/// Non-canonical types are useful for emitting diagnostics, without losing
1475/// information about typedefs being used. Canonical types are useful for type
1476/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1477/// about whether something has a particular form (e.g. is a function type),
1478/// because they implicitly, recursively, strip all typedefs out of a type.
1479///
1480/// Types, once created, are immutable.
1481///
1482class alignas(8) Type : public ExtQualsTypeCommonBase {
1483public:
1484 enum TypeClass {
1485#define TYPE(Class, Base) Class,
1486#define LAST_TYPE(Class) TypeLast = Class
1487#define ABSTRACT_TYPE(Class, Base)
1488#include "clang/AST/TypeNodes.inc"
1489 };
1490
1491private:
1492 /// Bitfields required by the Type class.
1493 class TypeBitfields {
1494 friend class Type;
1495 template <class T> friend class TypePropertyCache;
1496
1497 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1498 unsigned TC : 8;
1499
1500 /// Store information on the type dependency.
1501 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1502
1503 /// True if the cache (i.e. the bitfields here starting with
1504 /// 'Cache') is valid.
1505 mutable unsigned CacheValid : 1;
1506
1507 /// Linkage of this type.
1508 mutable unsigned CachedLinkage : 3;
1509
1510 /// Whether this type involves and local or unnamed types.
1511 mutable unsigned CachedLocalOrUnnamed : 1;
1512
1513 /// Whether this type comes from an AST file.
1514 mutable unsigned FromAST : 1;
1515
1516 bool isCacheValid() const {
1517 return CacheValid;
1518 }
1519
1520 Linkage getLinkage() const {
1521 assert(isCacheValid() && "getting linkage from invalid cache");
1522 return static_cast<Linkage>(CachedLinkage);
1523 }
1524
1525 bool hasLocalOrUnnamedType() const {
1526 assert(isCacheValid() && "getting linkage from invalid cache");
1527 return CachedLocalOrUnnamed;
1528 }
1529 };
1530 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1531
1532protected:
1533 // These classes allow subclasses to somewhat cleanly pack bitfields
1534 // into Type.
1535
1536 class ArrayTypeBitfields {
1537 friend class ArrayType;
1538
1539 unsigned : NumTypeBits;
1540
1541 /// CVR qualifiers from declarations like
1542 /// 'int X[static restrict 4]'. For function parameters only.
1543 unsigned IndexTypeQuals : 3;
1544
1545 /// Storage class qualifiers from declarations like
1546 /// 'int X[static restrict 4]'. For function parameters only.
1547 /// Actually an ArrayType::ArraySizeModifier.
1548 unsigned SizeModifier : 3;
1549 };
1550
1551 class ConstantArrayTypeBitfields {
1552 friend class ConstantArrayType;
1553
1554 unsigned : NumTypeBits + 3 + 3;
1555
1556 /// Whether we have a stored size expression.
1557 unsigned HasStoredSizeExpr : 1;
1558 };
1559
1560 class BuiltinTypeBitfields {
1561 friend class BuiltinType;
1562
1563 unsigned : NumTypeBits;
1564
1565 /// The kind (BuiltinType::Kind) of builtin type this is.
1566 unsigned Kind : 8;
1567 };
1568
1569 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1570 /// Only common bits are stored here. Additional uncommon bits are stored
1571 /// in a trailing object after FunctionProtoType.
1572 class FunctionTypeBitfields {
1573 friend class FunctionProtoType;
1574 friend class FunctionType;
1575
1576 unsigned : NumTypeBits;
1577
1578 /// Extra information which affects how the function is called, like
1579 /// regparm and the calling convention.
1580 unsigned ExtInfo : 13;
1581
1582 /// The ref-qualifier associated with a \c FunctionProtoType.
1583 ///
1584 /// This is a value of type \c RefQualifierKind.
1585 unsigned RefQualifier : 2;
1586
1587 /// Used only by FunctionProtoType, put here to pack with the
1588 /// other bitfields.
1589 /// The qualifiers are part of FunctionProtoType because...
1590 ///
1591 /// C++ 8.3.5p4: The return type, the parameter type list and the
1592 /// cv-qualifier-seq, [...], are part of the function type.
1593 unsigned FastTypeQuals : Qualifiers::FastWidth;
1594 /// Whether this function has extended Qualifiers.
1595 unsigned HasExtQuals : 1;
1596
1597 /// The number of parameters this function has, not counting '...'.
1598 /// According to [implimits] 8 bits should be enough here but this is
1599 /// somewhat easy to exceed with metaprogramming and so we would like to
1600 /// keep NumParams as wide as reasonably possible.
1601 unsigned NumParams : 16;
1602
1603 /// The type of exception specification this function has.
1604 unsigned ExceptionSpecType : 4;
1605
1606 /// Whether this function has extended parameter information.
1607 unsigned HasExtParameterInfos : 1;
1608
1609 /// Whether the function is variadic.
1610 unsigned Variadic : 1;
1611
1612 /// Whether this function has a trailing return type.
1613 unsigned HasTrailingReturn : 1;
1614 };
1615
1616 class ObjCObjectTypeBitfields {
1617 friend class ObjCObjectType;
1618
1619 unsigned : NumTypeBits;
1620
1621 /// The number of type arguments stored directly on this object type.
1622 unsigned NumTypeArgs : 7;
1623
1624 /// The number of protocols stored directly on this object type.
1625 unsigned NumProtocols : 6;
1626
1627 /// Whether this is a "kindof" type.
1628 unsigned IsKindOf : 1;
1629 };
1630
1631 class ReferenceTypeBitfields {
1632 friend class ReferenceType;
1633
1634 unsigned : NumTypeBits;
1635
1636 /// True if the type was originally spelled with an lvalue sigil.
1637 /// This is never true of rvalue references but can also be false
1638 /// on lvalue references because of C++0x [dcl.typedef]p9,
1639 /// as follows:
1640 ///
1641 /// typedef int &ref; // lvalue, spelled lvalue
1642 /// typedef int &&rvref; // rvalue
1643 /// ref &a; // lvalue, inner ref, spelled lvalue
1644 /// ref &&a; // lvalue, inner ref
1645 /// rvref &a; // lvalue, inner ref, spelled lvalue
1646 /// rvref &&a; // rvalue, inner ref
1647 unsigned SpelledAsLValue : 1;
1648
1649 /// True if the inner type is a reference type. This only happens
1650 /// in non-canonical forms.
1651 unsigned InnerRef : 1;
1652 };
1653
1654 class TypeWithKeywordBitfields {
1655 friend class TypeWithKeyword;
1656
1657 unsigned : NumTypeBits;
1658
1659 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1660 unsigned Keyword : 8;
1661 };
1662
1663 enum { NumTypeWithKeywordBits = 8 };
1664
1665 class ElaboratedTypeBitfields {
1666 friend class ElaboratedType;
1667
1668 unsigned : NumTypeBits;
1669 unsigned : NumTypeWithKeywordBits;
1670
1671 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1672 unsigned HasOwnedTagDecl : 1;
1673 };
1674
1675 class VectorTypeBitfields {
1676 friend class VectorType;
1677 friend class DependentVectorType;
1678
1679 unsigned : NumTypeBits;
1680
1681 /// The kind of vector, either a generic vector type or some
1682 /// target-specific vector type such as for AltiVec or Neon.
1683 unsigned VecKind : 3;
1684 /// The number of elements in the vector.
1685 uint32_t NumElements;
1686 };
1687
1688 class AttributedTypeBitfields {
1689 friend class AttributedType;
1690
1691 unsigned : NumTypeBits;
1692
1693 /// An AttributedType::Kind
1694 unsigned AttrKind : 32 - NumTypeBits;
1695 };
1696
1697 class AutoTypeBitfields {
1698 friend class AutoType;
1699
1700 unsigned : NumTypeBits;
1701
1702 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1703 /// or '__auto_type'? AutoTypeKeyword value.
1704 unsigned Keyword : 2;
1705
1706 /// The number of template arguments in the type-constraints, which is
1707 /// expected to be able to hold at least 1024 according to [implimits].
1708 /// However as this limit is somewhat easy to hit with template
1709 /// metaprogramming we'd prefer to keep it as large as possible.
1710 /// At the moment it has been left as a non-bitfield since this type
1711 /// safely fits in 64 bits as an unsigned, so there is no reason to
1712 /// introduce the performance impact of a bitfield.
1713 unsigned NumArgs;
1714 };
1715
1716 class SubstTemplateTypeParmPackTypeBitfields {
1717 friend class SubstTemplateTypeParmPackType;
1718
1719 unsigned : NumTypeBits;
1720
1721 /// The number of template arguments in \c Arguments, which is
1722 /// expected to be able to hold at least 1024 according to [implimits].
1723 /// However as this limit is somewhat easy to hit with template
1724 /// metaprogramming we'd prefer to keep it as large as possible.
1725 /// At the moment it has been left as a non-bitfield since this type
1726 /// safely fits in 64 bits as an unsigned, so there is no reason to
1727 /// introduce the performance impact of a bitfield.
1728 unsigned NumArgs;
1729 };
1730
1731 class TemplateSpecializationTypeBitfields {
1732 friend class TemplateSpecializationType;
1733
1734 unsigned : NumTypeBits;
1735
1736 /// Whether this template specialization type is a substituted type alias.
1737 unsigned TypeAlias : 1;
1738
1739 /// The number of template arguments named in this class template
1740 /// specialization, which is expected to be able to hold at least 1024
1741 /// according to [implimits]. However, as this limit is somewhat easy to
1742 /// hit with template metaprogramming we'd prefer to keep it as large
1743 /// as possible. At the moment it has been left as a non-bitfield since
1744 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1745 /// to introduce the performance impact of a bitfield.
1746 unsigned NumArgs;
1747 };
1748
1749 class DependentTemplateSpecializationTypeBitfields {
1750 friend class DependentTemplateSpecializationType;
1751
1752 unsigned : NumTypeBits;
1753 unsigned : NumTypeWithKeywordBits;
1754
1755 /// The number of template arguments named in this class template
1756 /// specialization, which is expected to be able to hold at least 1024
1757 /// according to [implimits]. However, as this limit is somewhat easy to
1758 /// hit with template metaprogramming we'd prefer to keep it as large
1759 /// as possible. At the moment it has been left as a non-bitfield since
1760 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1761 /// to introduce the performance impact of a bitfield.
1762 unsigned NumArgs;
1763 };
1764
1765 class PackExpansionTypeBitfields {
1766 friend class PackExpansionType;
1767
1768 unsigned : NumTypeBits;
1769
1770 /// The number of expansions that this pack expansion will
1771 /// generate when substituted (+1), which is expected to be able to
1772 /// hold at least 1024 according to [implimits]. However, as this limit
1773 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1774 /// keep it as large as possible. At the moment it has been left as a
1775 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1776 /// there is no reason to introduce the performance impact of a bitfield.
1777 ///
1778 /// This field will only have a non-zero value when some of the parameter
1779 /// packs that occur within the pattern have been substituted but others
1780 /// have not.
1781 unsigned NumExpansions;
1782 };
1783
1784 union {
1785 TypeBitfields TypeBits;
1786 ArrayTypeBitfields ArrayTypeBits;
1787 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1788 AttributedTypeBitfields AttributedTypeBits;
1789 AutoTypeBitfields AutoTypeBits;
1790 BuiltinTypeBitfields BuiltinTypeBits;
1791 FunctionTypeBitfields FunctionTypeBits;
1792 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1793 ReferenceTypeBitfields ReferenceTypeBits;
1794 TypeWithKeywordBitfields TypeWithKeywordBits;
1795 ElaboratedTypeBitfields ElaboratedTypeBits;
1796 VectorTypeBitfields VectorTypeBits;
1797 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1798 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1799 DependentTemplateSpecializationTypeBitfields
1800 DependentTemplateSpecializationTypeBits;
1801 PackExpansionTypeBitfields PackExpansionTypeBits;
1802 };
1803
1804private:
1805 template <class T> friend class TypePropertyCache;
1806
1807 /// Set whether this type comes from an AST file.
1808 void setFromAST(bool V = true) const {
1809 TypeBits.FromAST = V;
1810 }
1811
1812protected:
1813 friend class ASTContext;
1814
1815 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1816 : ExtQualsTypeCommonBase(this,
1817 canon.isNull() ? QualType(this_(), 0) : canon) {
1818 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1819 "changing bitfields changed sizeof(Type)!");
1820 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1821 "Insufficient alignment!");
1822 TypeBits.TC = tc;
1823 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1824 TypeBits.CacheValid = false;
1825 TypeBits.CachedLocalOrUnnamed = false;
1826 TypeBits.CachedLinkage = NoLinkage;
1827 TypeBits.FromAST = false;
1828 }
1829
1830 // silence VC++ warning C4355: 'this' : used in base member initializer list
1831 Type *this_() { return this; }
1832
1833 void setDependence(TypeDependence D) {
1834 TypeBits.Dependence = static_cast<unsigned>(D);
1835 }
1836
1837 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1838
1839public:
1840 friend class ASTReader;
1841 friend class ASTWriter;
1842 template <class T> friend class serialization::AbstractTypeReader;
1843 template <class T> friend class serialization::AbstractTypeWriter;
1844
1845 Type(const Type &) = delete;
1846 Type(Type &&) = delete;
1847 Type &operator=(const Type &) = delete;
1848 Type &operator=(Type &&) = delete;
1849
1850 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1851
1852 /// Whether this type comes from an AST file.
1853 bool isFromAST() const { return TypeBits.FromAST; }
1854
1855 /// Whether this type is or contains an unexpanded parameter
1856 /// pack, used to support C++0x variadic templates.
1857 ///
1858 /// A type that contains a parameter pack shall be expanded by the
1859 /// ellipsis operator at some point. For example, the typedef in the
1860 /// following example contains an unexpanded parameter pack 'T':
1861 ///
1862 /// \code
1863 /// template<typename ...T>
1864 /// struct X {
1865 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1866 /// };
1867 /// \endcode
1868 ///
1869 /// Note that this routine does not specify which
1870 bool containsUnexpandedParameterPack() const {
1871 return getDependence() & TypeDependence::UnexpandedPack;
1872 }
1873
1874 /// Determines if this type would be canonical if it had no further
1875 /// qualification.
1876 bool isCanonicalUnqualified() const {
1877 return CanonicalType == QualType(this, 0);
1878 }
1879
1880 /// Pull a single level of sugar off of this locally-unqualified type.
1881 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1882 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1883 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1884
1885 /// As an extension, we classify types as one of "sized" or "sizeless";
1886 /// every type is one or the other. Standard types are all sized;
1887 /// sizeless types are purely an extension.
1888 ///
1889 /// Sizeless types contain data with no specified size, alignment,
1890 /// or layout.
1891 bool isSizelessType() const;
1892 bool isSizelessBuiltinType() const;
1893
1894 /// Determines if this is a sizeless type supported by the
1895 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1896 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1897 bool isVLSTBuiltinType() const;
1898
1899 /// Returns the representative type for the element of an SVE builtin type.
1900 /// This is used to represent fixed-length SVE vectors created with the
1901 /// 'arm_sve_vector_bits' type attribute as VectorType.
1902 QualType getSveEltType(const ASTContext &Ctx) const;
1903
1904 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1905 /// object types, function types, and incomplete types.
1906
1907 /// Return true if this is an incomplete type.
1908 /// A type that can describe objects, but which lacks information needed to
1909 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1910 /// routine will need to determine if the size is actually required.
1911 ///
1912 /// Def If non-null, and the type refers to some kind of declaration
1913 /// that can be completed (such as a C struct, C++ class, or Objective-C
1914 /// class), will be set to the declaration.
1915 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1916
1917 /// Return true if this is an incomplete or object
1918 /// type, in other words, not a function type.
1919 bool isIncompleteOrObjectType() const {
1920 return !isFunctionType();
1921 }
1922
1923 /// Determine whether this type is an object type.
1924 bool isObjectType() const {
1925 // C++ [basic.types]p8:
1926 // An object type is a (possibly cv-qualified) type that is not a
1927 // function type, not a reference type, and not a void type.
1928 return !isReferenceType() && !isFunctionType() && !isVoidType();
1929 }
1930
1931 /// Return true if this is a literal type
1932 /// (C++11 [basic.types]p10)
1933 bool isLiteralType(const ASTContext &Ctx) const;
1934
1935 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1936 bool isStructuralType() const;
1937
1938 /// Test if this type is a standard-layout type.
1939 /// (C++0x [basic.type]p9)
1940 bool isStandardLayoutType() const;
1941
1942 /// Helper methods to distinguish type categories. All type predicates
1943 /// operate on the canonical type, ignoring typedefs and qualifiers.
1944
1945 /// Returns true if the type is a builtin type.
1946 bool isBuiltinType() const;
1947
1948 /// Test for a particular builtin type.
1949 bool isSpecificBuiltinType(unsigned K) const;
1950
1951 /// Test for a type which does not represent an actual type-system type but
1952 /// is instead used as a placeholder for various convenient purposes within
1953 /// Clang. All such types are BuiltinTypes.
1954 bool isPlaceholderType() const;
1955 const BuiltinType *getAsPlaceholderType() const;
1956
1957 /// Test for a specific placeholder type.
1958 bool isSpecificPlaceholderType(unsigned K) const;
1959
1960 /// Test for a placeholder type other than Overload; see
1961 /// BuiltinType::isNonOverloadPlaceholderType.
1962 bool isNonOverloadPlaceholderType() const;
1963
1964 /// isIntegerType() does *not* include complex integers (a GCC extension).
1965 /// isComplexIntegerType() can be used to test for complex integers.
1966 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1967 bool isEnumeralType() const;
1968
1969 /// Determine whether this type is a scoped enumeration type.
1970 bool isScopedEnumeralType() const;
1971 bool isBooleanType() const;
1972 bool isCharType() const;
1973 bool isWideCharType() const;
1974 bool isChar8Type() const;
1975 bool isChar16Type() const;
1976 bool isChar32Type() const;
1977 bool isAnyCharacterType() const;
1978 bool isIntegralType(const ASTContext &Ctx) const;
1979
1980 /// Determine whether this type is an integral or enumeration type.
1981 bool isIntegralOrEnumerationType() const;
1982
1983 /// Determine whether this type is an integral or unscoped enumeration type.
1984 bool isIntegralOrUnscopedEnumerationType() const;
1985 bool isUnscopedEnumerationType() const;
1986
1987 /// Floating point categories.
1988 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1989 /// isComplexType() does *not* include complex integers (a GCC extension).
1990 /// isComplexIntegerType() can be used to test for complex integers.
1991 bool isComplexType() const; // C99 6.2.5p11 (complex)
1992 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1993 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1994 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1995 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1996 bool isBFloat16Type() const;
1997 bool isFloat128Type() const;
1998 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1999 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2000 bool isVoidType() const; // C99 6.2.5p19
2001 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2002 bool isAggregateType() const;
2003 bool isFundamentalType() const;
2004 bool isCompoundType() const;
2005
2006 // Type Predicates: Check to see if this type is structurally the specified
2007 // type, ignoring typedefs and qualifiers.
2008 bool isFunctionType() const;
2009 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2010 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2011 bool isPointerType() const;
2012 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2013 bool isBlockPointerType() const;
2014 bool isVoidPointerType() const;
2015 bool isReferenceType() const;
2016 bool isLValueReferenceType() const;
2017 bool isRValueReferenceType() const;
2018 bool isObjectPointerType() const;
2019 bool isFunctionPointerType() const;
2020 bool isFunctionReferenceType() const;
2021 bool isMemberPointerType() const;
2022 bool isMemberFunctionPointerType() const;
2023 bool isMemberDataPointerType() const;
2024 bool isArrayType() const;
2025 bool isConstantArrayType() const;
2026 bool isIncompleteArrayType() const;
2027 bool isVariableArrayType() const;
2028 bool isDependentSizedArrayType() const;
2029 bool isRecordType() const;
2030 bool isClassType() const;
2031 bool isStructureType() const;
2032 bool isObjCBoxableRecordType() const;
2033 bool isInterfaceType() const;
2034 bool isStructureOrClassType() const;
2035 bool isUnionType() const;
2036 bool isComplexIntegerType() const; // GCC _Complex integer type.
2037 bool isVectorType() const; // GCC vector type.
2038 bool isExtVectorType() const; // Extended vector type.
2039 bool isMatrixType() const; // Matrix type.
2040 bool isConstantMatrixType() const; // Constant matrix type.
2041 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2042 bool isObjCObjectPointerType() const; // pointer to ObjC object
2043 bool isObjCRetainableType() const; // ObjC object or block pointer
2044 bool isObjCLifetimeType() const; // (array of)* retainable type
2045 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2046 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2047 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2048 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2049 // for the common case.
2050 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2051 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2052 bool isObjCQualifiedIdType() const; // id<foo>
2053 bool isObjCQualifiedClassType() const; // Class<foo>
2054 bool isObjCObjectOrInterfaceType() const;
2055 bool isObjCIdType() const; // id
2056 bool isDecltypeType() const;
2057 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2058 /// qualifier?
2059 ///
2060 /// This approximates the answer to the following question: if this
2061 /// translation unit were compiled in ARC, would this type be qualified
2062 /// with __unsafe_unretained?
2063 bool isObjCInertUnsafeUnretainedType() const {
2064 return hasAttr(attr::ObjCInertUnsafeUnretained);
2065 }
2066
2067 /// Whether the type is Objective-C 'id' or a __kindof type of an
2068 /// object type, e.g., __kindof NSView * or __kindof id
2069 /// <NSCopying>.
2070 ///
2071 /// \param bound Will be set to the bound on non-id subtype types,
2072 /// which will be (possibly specialized) Objective-C class type, or
2073 /// null for 'id.
2074 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2075 const ObjCObjectType *&bound) const;
2076
2077 bool isObjCClassType() const; // Class
2078
2079 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2080 /// Class type, e.g., __kindof Class <NSCopying>.
2081 ///
2082 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2083 /// here because Objective-C's type system cannot express "a class
2084 /// object for a subclass of NSFoo".
2085 bool isObjCClassOrClassKindOfType() const;
2086
2087 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2088 bool isObjCSelType() const; // Class
2089 bool isObjCBuiltinType() const; // 'id' or 'Class'
2090 bool isObjCARCBridgableType() const;
2091 bool isCARCBridgableType() const;
2092 bool isTemplateTypeParmType() const; // C++ template type parameter
2093 bool isNullPtrType() const; // C++11 std::nullptr_t
2094 bool isNothrowT() const; // C++ std::nothrow_t
2095 bool isAlignValT() const; // C++17 std::align_val_t
2096 bool isStdByteType() const; // C++17 std::byte
2097 bool isAtomicType() const; // C11 _Atomic()
2098 bool isUndeducedAutoType() const; // C++11 auto or
2099 // C++14 decltype(auto)
2100 bool isTypedefNameType() const; // typedef or alias template
2101
2102#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2103 bool is##Id##Type() const;
2104#include "clang/Basic/OpenCLImageTypes.def"
2105
2106 bool isImageType() const; // Any OpenCL image type
2107
2108 bool isSamplerT() const; // OpenCL sampler_t
2109 bool isEventT() const; // OpenCL event_t
2110 bool isClkEventT() const; // OpenCL clk_event_t
2111 bool isQueueT() const; // OpenCL queue_t
2112 bool isReserveIDT() const; // OpenCL reserve_id_t
2113
2114#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2115 bool is##Id##Type() const;
2116#include "clang/Basic/OpenCLExtensionTypes.def"
2117 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2118 bool isOCLIntelSubgroupAVCType() const;
2119 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2120
2121 bool isPipeType() const; // OpenCL pipe type
2122 bool isExtIntType() const; // Extended Int Type
2123 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2124
2125 /// Determines if this type, which must satisfy
2126 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2127 /// than implicitly __strong.
2128 bool isObjCARCImplicitlyUnretainedType() const;
2129
2130 /// Check if the type is the CUDA device builtin surface type.
2131 bool isCUDADeviceBuiltinSurfaceType() const;
2132 /// Check if the type is the CUDA device builtin texture type.
2133 bool isCUDADeviceBuiltinTextureType() const;
2134
2135 /// Return the implicit lifetime for this type, which must not be dependent.
2136 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2137
2138 enum ScalarTypeKind {
2139 STK_CPointer,
2140 STK_BlockPointer,
2141 STK_ObjCObjectPointer,
2142 STK_MemberPointer,
2143 STK_Bool,
2144 STK_Integral,
2145 STK_Floating,
2146 STK_IntegralComplex,
2147 STK_FloatingComplex,
2148 STK_FixedPoint
2149 };
2150
2151 /// Given that this is a scalar type, classify it.
2152 ScalarTypeKind getScalarTypeKind() const;
2153
2154 TypeDependence getDependence() const {
2155 return static_cast<TypeDependence>(TypeBits.Dependence);
2156 }
2157
2158 /// Whether this type is an error type.
2159 bool containsErrors() const {
2160 return getDependence() & TypeDependence::Error;
2161 }
2162
2163 /// Whether this type is a dependent type, meaning that its definition
2164 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2165 bool isDependentType() const {
2166 return getDependence() & TypeDependence::Dependent;
2167 }
2168
2169 /// Determine whether this type is an instantiation-dependent type,
2170 /// meaning that the type involves a template parameter (even if the
2171 /// definition does not actually depend on the type substituted for that
2172 /// template parameter).
2173 bool isInstantiationDependentType() const {
2174 return getDependence() & TypeDependence::Instantiation;
2175 }
2176
2177 /// Determine whether this type is an undeduced type, meaning that
2178 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2179 /// deduced.
2180 bool isUndeducedType() const;
2181
2182 /// Whether this type is a variably-modified type (C99 6.7.5).
2183 bool isVariablyModifiedType() const {
2184 return getDependence() & TypeDependence::VariablyModified;
2185 }
2186
2187 /// Whether this type involves a variable-length array type
2188 /// with a definite size.
2189 bool hasSizedVLAType() const;
2190
2191 /// Whether this type is or contains a local or unnamed type.
2192 bool hasUnnamedOrLocalType() const;
2193
2194 bool isOverloadableType() const;
2195
2196 /// Determine wither this type is a C++ elaborated-type-specifier.
2197 bool isElaboratedTypeSpecifier() const;
2198
2199 bool canDecayToPointerType() const;
2200
2201 /// Whether this type is represented natively as a pointer. This includes
2202 /// pointers, references, block pointers, and Objective-C interface,
2203 /// qualified id, and qualified interface types, as well as nullptr_t.
2204 bool hasPointerRepresentation() const;
2205
2206 /// Whether this type can represent an objective pointer type for the
2207 /// purpose of GC'ability
2208 bool hasObjCPointerRepresentation() const;
2209
2210 /// Determine whether this type has an integer representation
2211 /// of some sort, e.g., it is an integer type or a vector.
2212 bool hasIntegerRepresentation() const;
2213
2214 /// Determine whether this type has an signed integer representation
2215 /// of some sort, e.g., it is an signed integer type or a vector.
2216 bool hasSignedIntegerRepresentation() const;
2217
2218 /// Determine whether this type has an unsigned integer representation
2219 /// of some sort, e.g., it is an unsigned integer type or a vector.
2220 bool hasUnsignedIntegerRepresentation() const;
2221
2222 /// Determine whether this type has a floating-point representation
2223 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2224 bool hasFloatingRepresentation() const;
2225
2226 // Type Checking Functions: Check to see if this type is structurally the
2227 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2228 // the best type we can.
2229 const RecordType *getAsStructureType() const;
2230 /// NOTE: getAs*ArrayType are methods on ASTContext.
2231 const RecordType *getAsUnionType() const;
2232 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2233 const ObjCObjectType *getAsObjCInterfaceType() const;
2234
2235 // The following is a convenience method that returns an ObjCObjectPointerType
2236 // for object declared using an interface.
2237 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2238 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2239 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2240 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2241
2242 /// Retrieves the CXXRecordDecl that this type refers to, either
2243 /// because the type is a RecordType or because it is the injected-class-name
2244 /// type of a class template or class template partial specialization.
2245 CXXRecordDecl *getAsCXXRecordDecl() const;
2246
2247 /// Retrieves the RecordDecl this type refers to.
2248 RecordDecl *getAsRecordDecl() const;
2249
2250 /// Retrieves the TagDecl that this type refers to, either
2251 /// because the type is a TagType or because it is the injected-class-name
2252 /// type of a class template or class template partial specialization.
2253 TagDecl *getAsTagDecl() const;
2254
2255 /// If this is a pointer or reference to a RecordType, return the
2256 /// CXXRecordDecl that the type refers to.
2257 ///
2258 /// If this is not a pointer or reference, or the type being pointed to does
2259 /// not refer to a CXXRecordDecl, returns NULL.
2260 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2261
2262 /// Get the DeducedType whose type will be deduced for a variable with
2263 /// an initializer of this type. This looks through declarators like pointer
2264 /// types, but not through decltype or typedefs.
2265 DeducedType *getContainedDeducedType() const;
2266
2267 /// Get the AutoType whose type will be deduced for a variable with
2268 /// an initializer of this type. This looks through declarators like pointer
2269 /// types, but not through decltype or typedefs.
2270 AutoType *getContainedAutoType() const {
2271 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2272 }
2273
2274 /// Determine whether this type was written with a leading 'auto'
2275 /// corresponding to a trailing return type (possibly for a nested
2276 /// function type within a pointer to function type or similar).
2277 bool hasAutoForTrailingReturnType() const;
2278
2279 /// Member-template getAs<specific type>'. Look through sugar for
2280 /// an instance of \<specific type>. This scheme will eventually
2281 /// replace the specific getAsXXXX methods above.
2282 ///
2283 /// There are some specializations of this member template listed
2284 /// immediately following this class.
2285 template <typename T> const T *getAs() const;
2286
2287 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2288 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2289 /// This is used when you need to walk over sugar nodes that represent some
2290 /// kind of type adjustment from a type that was written as a \<specific type>
2291 /// to another type that is still canonically a \<specific type>.
2292 template <typename T> const T *getAsAdjusted() const;
2293
2294 /// A variant of getAs<> for array types which silently discards
2295 /// qualifiers from the outermost type.
2296 const ArrayType *getAsArrayTypeUnsafe() const;
2297
2298 /// Member-template castAs<specific type>. Look through sugar for
2299 /// the underlying instance of \<specific type>.
2300 ///
2301 /// This method has the same relationship to getAs<T> as cast<T> has
2302 /// to dyn_cast<T>; which is to say, the underlying type *must*
2303 /// have the intended type, and this method will never return null.
2304 template <typename T> const T *castAs() const;
2305
2306 /// A variant of castAs<> for array type which silently discards
2307 /// qualifiers from the outermost type.
2308 const ArrayType *castAsArrayTypeUnsafe() const;
2309
2310 /// Determine whether this type had the specified attribute applied to it
2311 /// (looking through top-level type sugar).
2312 bool hasAttr(attr::Kind AK) const;
2313
2314 /// Get the base element type of this type, potentially discarding type
2315 /// qualifiers. This should never be used when type qualifiers
2316 /// are meaningful.
2317 const Type *getBaseElementTypeUnsafe() const;
2318
2319 /// If this is an array type, return the element type of the array,
2320 /// potentially with type qualifiers missing.
2321 /// This should never be used when type qualifiers are meaningful.
2322 const Type *getArrayElementTypeNoTypeQual() const;
2323
2324 /// If this is a pointer type, return the pointee type.
2325 /// If this is an array type, return the array element type.
2326 /// This should never be used when type qualifiers are meaningful.
2327 const Type *getPointeeOrArrayElementType() const;
2328
2329 /// If this is a pointer, ObjC object pointer, or block
2330 /// pointer, this returns the respective pointee.
2331 QualType getPointeeType() const;
2332
2333 /// Return the specified type with any "sugar" removed from the type,
2334 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2335 const Type *getUnqualifiedDesugaredType() const;
2336
2337 /// More type predicates useful for type checking/promotion
2338 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2339
2340 /// Return true if this is an integer type that is
2341 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2342 /// or an enum decl which has a signed representation.
2343 bool isSignedIntegerType() const;
2344
2345 /// Return true if this is an integer type that is
2346 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2347 /// or an enum decl which has an unsigned representation.
2348 bool isUnsignedIntegerType() const;
2349
2350 /// Determines whether this is an integer type that is signed or an
2351 /// enumeration types whose underlying type is a signed integer type.
2352 bool isSignedIntegerOrEnumerationType() const;
2353
2354 /// Determines whether this is an integer type that is unsigned or an
2355 /// enumeration types whose underlying type is a unsigned integer type.
2356 bool isUnsignedIntegerOrEnumerationType() const;
2357
2358 /// Return true if this is a fixed point type according to
2359 /// ISO/IEC JTC1 SC22 WG14 N1169.
2360 bool isFixedPointType() const;
2361
2362 /// Return true if this is a fixed point or integer type.
2363 bool isFixedPointOrIntegerType() const;
2364
2365 /// Return true if this is a saturated fixed point type according to
2366 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2367 bool isSaturatedFixedPointType() const;
2368
2369 /// Return true if this is a saturated fixed point type according to
2370 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2371 bool isUnsaturatedFixedPointType() const;
2372
2373 /// Return true if this is a fixed point type that is signed according
2374 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2375 bool isSignedFixedPointType() const;
2376
2377 /// Return true if this is a fixed point type that is unsigned according
2378 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2379 bool isUnsignedFixedPointType() const;
2380
2381 /// Return true if this is not a variable sized type,
2382 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2383 /// incomplete types.
2384 bool isConstantSizeType() const;
2385
2386 /// Returns true if this type can be represented by some
2387 /// set of type specifiers.
2388 bool isSpecifierType() const;
2389
2390 /// Determine the linkage of this type.
2391 Linkage getLinkage() const;
2392
2393 /// Determine the visibility of this type.
2394 Visibility getVisibility() const {
2395 return getLinkageAndVisibility().getVisibility();
2396 }
2397
2398 /// Return true if the visibility was explicitly set is the code.
2399 bool isVisibilityExplicit() const {
2400 return getLinkageAndVisibility().isVisibilityExplicit();
2401 }
2402
2403 /// Determine the linkage and visibility of this type.
2404 LinkageInfo getLinkageAndVisibility() const;
2405
2406 /// True if the computed linkage is valid. Used for consistency
2407 /// checking. Should always return true.
2408 bool isLinkageValid() const;
2409
2410 /// Determine the nullability of the given type.
2411 ///
2412 /// Note that nullability is only captured as sugar within the type
2413 /// system, not as part of the canonical type, so nullability will
2414 /// be lost by canonicalization and desugaring.
2415 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2416
2417 /// Determine whether the given type can have a nullability
2418 /// specifier applied to it, i.e., if it is any kind of pointer type.
2419 ///
2420 /// \param ResultIfUnknown The value to return if we don't yet know whether
2421 /// this type can have nullability because it is dependent.
2422 bool canHaveNullability(bool ResultIfUnknown = true) const;
2423
2424 /// Retrieve the set of substitutions required when accessing a member
2425 /// of the Objective-C receiver type that is declared in the given context.
2426 ///
2427 /// \c *this is the type of the object we're operating on, e.g., the
2428 /// receiver for a message send or the base of a property access, and is
2429 /// expected to be of some object or object pointer type.
2430 ///
2431 /// \param dc The declaration context for which we are building up a
2432 /// substitution mapping, which should be an Objective-C class, extension,
2433 /// category, or method within.
2434 ///
2435 /// \returns an array of type arguments that can be substituted for
2436 /// the type parameters of the given declaration context in any type described
2437 /// within that context, or an empty optional to indicate that no
2438 /// substitution is required.
2439 Optional<ArrayRef<QualType>>
2440 getObjCSubstitutions(const DeclContext *dc) const;
2441
2442 /// Determines if this is an ObjC interface type that may accept type
2443 /// parameters.
2444 bool acceptsObjCTypeParams() const;
2445
2446 const char *getTypeClassName() const;
2447
2448 QualType getCanonicalTypeInternal() const {
2449 return CanonicalType;
2450 }
2451
2452 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2453 void dump() const;
2454 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2455};
2456
2457/// This will check for a TypedefType by removing any existing sugar
2458/// until it reaches a TypedefType or a non-sugared type.
2459template <> const TypedefType *Type::getAs() const;
2460
2461/// This will check for a TemplateSpecializationType by removing any
2462/// existing sugar until it reaches a TemplateSpecializationType or a
2463/// non-sugared type.
2464template <> const TemplateSpecializationType *Type::getAs() const;
2465
2466/// This will check for an AttributedType by removing any existing sugar
2467/// until it reaches an AttributedType or a non-sugared type.
2468template <> const AttributedType *Type::getAs() const;
2469
2470// We can do canonical leaf types faster, because we don't have to
2471// worry about preserving child type decoration.
2472#define TYPE(Class, Base)
2473#define LEAF_TYPE(Class) \
2474template <> inline const Class##Type *Type::getAs() const { \
2475 return dyn_cast<Class##Type>(CanonicalType); \
2476} \
2477template <> inline const Class##Type *Type::castAs() const { \
2478 return cast<Class##Type>(CanonicalType); \
2479}
2480#include "clang/AST/TypeNodes.inc"
2481
2482/// This class is used for builtin types like 'int'. Builtin
2483/// types are always canonical and have a literal name field.
2484class BuiltinType : public Type {
2485public:
2486 enum Kind {
2487// OpenCL image types
2488#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2489#include "clang/Basic/OpenCLImageTypes.def"
2490// OpenCL extension types
2491#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2492#include "clang/Basic/OpenCLExtensionTypes.def"
2493// SVE Types
2494#define SVE_TYPE(Name, Id, SingletonId) Id,
2495#include "clang/Basic/AArch64SVEACLETypes.def"
2496// PPC MMA Types
2497#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2498#include "clang/Basic/PPCTypes.def"
2499// RVV Types
2500#define RVV_TYPE(Name, Id, SingletonId) Id,
2501#include "clang/Basic/RISCVVTypes.def"
2502// All other builtin types
2503#define BUILTIN_TYPE(Id, SingletonId) Id,
2504#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2505#include "clang/AST/BuiltinTypes.def"
2506 };
2507
2508private:
2509 friend class ASTContext; // ASTContext creates these.
2510
2511 BuiltinType(Kind K)
2512 : Type(Builtin, QualType(),
2513 K == Dependent ? TypeDependence::DependentInstantiation
2514 : TypeDependence::None) {
2515 BuiltinTypeBits.Kind = K;
2516 }
2517
2518public:
2519 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2520 StringRef getName(const PrintingPolicy &Policy) const;
2521
2522 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2523 // The StringRef is null-terminated.
2524 StringRef str = getName(Policy);
2525 assert(!str.empty() && str.data()[str.size()] == '\0');
2526 return str.data();
2527 }
2528
2529 bool isSugared() const { return false; }
2530 QualType desugar() const { return QualType(this, 0); }
2531
2532 bool isInteger() const {
2533 return getKind() >= Bool && getKind() <= Int128;
2534 }
2535
2536 bool isSignedInteger() const {
2537 return getKind() >= Char_S && getKind() <= Int128;
2538 }
2539
2540 bool isUnsignedInteger() const {
2541 return getKind() >= Bool && getKind() <= UInt128;
2542 }
2543
2544 bool isFloatingPoint() const {
2545 return getKind() >= Half && getKind() <= Float128;
2546 }
2547
2548 /// Determines whether the given kind corresponds to a placeholder type.
2549 static bool isPlaceholderTypeKind(Kind K) {
2550 return K >= Overload;
2551 }
2552
2553 /// Determines whether this type is a placeholder type, i.e. a type
2554 /// which cannot appear in arbitrary positions in a fully-formed
2555 /// expression.
2556 bool isPlaceholderType() const {
2557 return isPlaceholderTypeKind(getKind());
2558 }
2559
2560 /// Determines whether this type is a placeholder type other than
2561 /// Overload. Most placeholder types require only syntactic
2562 /// information about their context in order to be resolved (e.g.
2563 /// whether it is a call expression), which means they can (and
2564 /// should) be resolved in an earlier "phase" of analysis.
2565 /// Overload expressions sometimes pick up further information
2566 /// from their context, like whether the context expects a
2567 /// specific function-pointer type, and so frequently need
2568 /// special treatment.
2569 bool isNonOverloadPlaceholderType() const {
2570 return getKind() > Overload;
2571 }
2572
2573 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2574};
2575
2576/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2577/// types (_Complex float etc) as well as the GCC integer complex extensions.
2578class ComplexType : public Type, public llvm::FoldingSetNode {
2579 friend class ASTContext; // ASTContext creates these.
2580
2581 QualType ElementType;
2582
2583 ComplexType(QualType Element, QualType CanonicalPtr)
2584 : Type(Complex, CanonicalPtr, Element->getDependence()),
2585 ElementType(Element) {}
2586
2587public:
2588 QualType getElementType() const { return ElementType; }
2589
2590 bool isSugared() const { return false; }
2591 QualType desugar() const { return QualType(this, 0); }
2592
2593 void Profile(llvm::FoldingSetNodeID &ID) {
2594 Profile(ID, getElementType());
2595 }
2596
2597 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2598 ID.AddPointer(Element.getAsOpaquePtr());
2599 }
2600
2601 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2602};
2603
2604/// Sugar for parentheses used when specifying types.
2605class ParenType : public Type, public llvm::FoldingSetNode {
2606 friend class ASTContext; // ASTContext creates these.
2607
2608 QualType Inner;
2609
2610 ParenType(QualType InnerType, QualType CanonType)
2611 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2612
2613public:
2614 QualType getInnerType() const { return Inner; }
2615
2616 bool isSugared() const { return true; }
2617 QualType desugar() const { return getInnerType(); }
2618
2619 void Profile(llvm::FoldingSetNodeID &ID) {
2620 Profile(ID, getInnerType());
2621 }
2622
2623 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2624 Inner.Profile(ID);
2625 }
2626
2627 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2628};
2629
2630/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2631class PointerType : public Type, public llvm::FoldingSetNode {
2632 friend class ASTContext; // ASTContext creates these.
2633
2634 QualType PointeeType;
2635
2636 PointerType(QualType Pointee, QualType CanonicalPtr)
2637 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2638 PointeeType(Pointee) {}
2639
2640public:
2641 QualType getPointeeType() const { return PointeeType; }
2642
2643 bool isSugared() const { return false; }
2644 QualType desugar() const { return QualType(this, 0); }
2645
2646 void Profile(llvm::FoldingSetNodeID &ID) {
2647 Profile(ID, getPointeeType());
2648 }
2649
2650 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2651 ID.AddPointer(Pointee.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2655};
2656
2657/// Represents a type which was implicitly adjusted by the semantic
2658/// engine for arbitrary reasons. For example, array and function types can
2659/// decay, and function types can have their calling conventions adjusted.
2660class AdjustedType : public Type, public llvm::FoldingSetNode {
2661 QualType OriginalTy;
2662 QualType AdjustedTy;
2663
2664protected:
2665 friend class ASTContext; // ASTContext creates these.
2666
2667 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2668 QualType CanonicalPtr)
2669 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2670 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2671
2672public:
2673 QualType getOriginalType() const { return OriginalTy; }
2674 QualType getAdjustedType() const { return AdjustedTy; }
2675
2676 bool isSugared() const { return true; }
2677 QualType desugar() const { return AdjustedTy; }
2678
2679 void Profile(llvm::FoldingSetNodeID &ID) {
2680 Profile(ID, OriginalTy, AdjustedTy);
2681 }
2682
2683 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2684 ID.AddPointer(Orig.getAsOpaquePtr());
2685 ID.AddPointer(New.getAsOpaquePtr());
2686 }
2687
2688 static bool classof(const Type *T) {
2689 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2690 }
2691};
2692
2693/// Represents a pointer type decayed from an array or function type.
2694class DecayedType : public AdjustedType {
2695 friend class ASTContext; // ASTContext creates these.
2696
2697 inline
2698 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2699
2700public:
2701 QualType getDecayedType() const { return getAdjustedType(); }
2702
2703 inline QualType getPointeeType() const;
2704
2705 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2706};
2707
2708/// Pointer to a block type.
2709/// This type is to represent types syntactically represented as
2710/// "void (^)(int)", etc. Pointee is required to always be a function type.
2711class BlockPointerType : public Type, public llvm::FoldingSetNode {
2712 friend class ASTContext; // ASTContext creates these.
2713
2714 // Block is some kind of pointer type
2715 QualType PointeeType;
2716
2717 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2718 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2719 PointeeType(Pointee) {}
2720
2721public:
2722 // Get the pointee type. Pointee is required to always be a function type.
2723 QualType getPointeeType() const { return PointeeType; }
2724
2725 bool isSugared() const { return false; }
2726 QualType desugar() const { return QualType(this, 0); }
2727
2728 void Profile(llvm::FoldingSetNodeID &ID) {
2729 Profile(ID, getPointeeType());
2730 }
2731
2732 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2733 ID.AddPointer(Pointee.getAsOpaquePtr());
2734 }
2735
2736 static bool classof(const Type *T) {
2737 return T->getTypeClass() == BlockPointer;
2738 }
2739};
2740
2741/// Base for LValueReferenceType and RValueReferenceType
2742class ReferenceType : public Type, public llvm::FoldingSetNode {
2743 QualType PointeeType;
2744
2745protected:
2746 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2747 bool SpelledAsLValue)
2748 : Type(tc, CanonicalRef, Referencee->getDependence()),
2749 PointeeType(Referencee) {
2750 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2751 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2752 }
2753
2754public:
2755 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2756 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2757
2758 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2759
2760 QualType getPointeeType() const {
2761 // FIXME: this might strip inner qualifiers; okay?
2762 const ReferenceType *T = this;
2763 while (T->isInnerRef())
2764 T = T->PointeeType->castAs<ReferenceType>();
2765 return T->PointeeType;
2766 }
2767
2768 void Profile(llvm::FoldingSetNodeID &ID) {
2769 Profile(ID, PointeeType, isSpelledAsLValue());
2770 }
2771
2772 static void Profile(llvm::FoldingSetNodeID &ID,
2773 QualType Referencee,
2774 bool SpelledAsLValue) {
2775 ID.AddPointer(Referencee.getAsOpaquePtr());
2776 ID.AddBoolean(SpelledAsLValue);
2777 }
2778
2779 static bool classof(const Type *T) {
2780 return T->getTypeClass() == LValueReference ||
2781 T->getTypeClass() == RValueReference;
2782 }
2783};
2784
2785/// An lvalue reference type, per C++11 [dcl.ref].
2786class LValueReferenceType : public ReferenceType {
2787 friend class ASTContext; // ASTContext creates these
2788
2789 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2790 bool SpelledAsLValue)
2791 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2792 SpelledAsLValue) {}
2793
2794public:
2795 bool isSugared() const { return false; }
2796 QualType desugar() const { return QualType(this, 0); }
2797
2798 static bool classof(const Type *T) {
2799 return T->getTypeClass() == LValueReference;
2800 }
2801};
2802
2803/// An rvalue reference type, per C++11 [dcl.ref].
2804class RValueReferenceType : public ReferenceType {
2805 friend class ASTContext; // ASTContext creates these
2806
2807 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2808 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2809
2810public:
2811 bool isSugared() const { return false; }
2812 QualType desugar() const { return QualType(this, 0); }
2813
2814 static bool classof(const Type *T) {
2815 return T->getTypeClass() == RValueReference;
2816 }
2817};
2818
2819/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2820///
2821/// This includes both pointers to data members and pointer to member functions.
2822class MemberPointerType : public Type, public llvm::FoldingSetNode {
2823 friend class ASTContext; // ASTContext creates these.
2824
2825 QualType PointeeType;
2826
2827 /// The class of which the pointee is a member. Must ultimately be a
2828 /// RecordType, but could be a typedef or a template parameter too.
2829 const Type *Class;
2830
2831 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2832 : Type(MemberPointer, CanonicalPtr,
2833 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2834 Pointee->getDependence()),
2835 PointeeType(Pointee), Class(Cls) {}
2836
2837public:
2838 QualType getPointeeType() const { return PointeeType; }
2839
2840 /// Returns true if the member type (i.e. the pointee type) is a
2841 /// function type rather than a data-member type.
2842 bool isMemberFunctionPointer() const {
2843 return PointeeType->isFunctionProtoType();
2844 }
2845
2846 /// Returns true if the member type (i.e. the pointee type) is a
2847 /// data type rather than a function type.
2848 bool isMemberDataPointer() const {
2849 return !PointeeType->isFunctionProtoType();
2850 }
2851
2852 const Type *getClass() const { return Class; }
2853 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2854
2855 bool isSugared() const { return false; }
2856 QualType desugar() const { return QualType(this, 0); }
2857
2858 void Profile(llvm::FoldingSetNodeID &ID) {
2859 Profile(ID, getPointeeType(), getClass());
2860 }
2861
2862 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2863 const Type *Class) {
2864 ID.AddPointer(Pointee.getAsOpaquePtr());
2865 ID.AddPointer(Class);
2866 }
2867
2868 static bool classof(const Type *T) {
2869 return T->getTypeClass() == MemberPointer;
2870 }
2871};
2872
2873/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2874class ArrayType : public Type, public llvm::FoldingSetNode {
2875public:
2876 /// Capture whether this is a normal array (e.g. int X[4])
2877 /// an array with a static size (e.g. int X[static 4]), or an array
2878 /// with a star size (e.g. int X[*]).
2879 /// 'static' is only allowed on function parameters.
2880 enum ArraySizeModifier {
2881 Normal, Static, Star
2882 };
2883
2884private:
2885 /// The element type of the array.
2886 QualType ElementType;
2887
2888protected:
2889 friend class ASTContext; // ASTContext creates these.
2890
2891 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2892 unsigned tq, const Expr *sz = nullptr);
2893
2894public:
2895 QualType getElementType() const { return ElementType; }
2896
2897 ArraySizeModifier getSizeModifier() const {
2898 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2899 }
2900
2901 Qualifiers getIndexTypeQualifiers() const {
2902 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2903 }
2904
2905 unsigned getIndexTypeCVRQualifiers() const {
2906 return ArrayTypeBits.IndexTypeQuals;
2907 }
2908
2909 static bool classof(const Type *T) {
2910 return T->getTypeClass() == ConstantArray ||
2911 T->getTypeClass() == VariableArray ||
2912 T->getTypeClass() == IncompleteArray ||
2913 T->getTypeClass() == DependentSizedArray;
2914 }
2915};
2916
2917/// Represents the canonical version of C arrays with a specified constant size.
2918/// For example, the canonical type for 'int A[4 + 4*100]' is a
2919/// ConstantArrayType where the element type is 'int' and the size is 404.
2920class ConstantArrayType final
2921 : public ArrayType,
2922 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2923 friend class ASTContext; // ASTContext creates these.
2924 friend TrailingObjects;
2925
2926 llvm::APInt Size; // Allows us to unique the type.
2927
2928 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2929 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2930 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2931 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2932 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2933 assert(!can.isNull() && "canonical constant array should not have size");
2934 *getTrailingObjects<const Expr*>() = sz;
2935 }
2936 }
2937
2938 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2939 return ConstantArrayTypeBits.HasStoredSizeExpr;
2940 }
2941
2942public:
2943 const llvm::APInt &getSize() const { return Size; }
2944 const Expr *getSizeExpr() const {
2945 return ConstantArrayTypeBits.HasStoredSizeExpr
2946 ? *getTrailingObjects<const Expr *>()
2947 : nullptr;
2948 }
2949 bool isSugared() const { return false; }
2950 QualType desugar() const { return QualType(this, 0); }
2951
2952 /// Determine the number of bits required to address a member of
2953 // an array with the given element type and number of elements.
2954 static unsigned getNumAddressingBits(const ASTContext &Context,
2955 QualType ElementType,
2956 const llvm::APInt &NumElements);
2957
2958 /// Determine the maximum number of active bits that an array's size
2959 /// can require, which limits the maximum size of the array.
2960 static unsigned getMaxSizeBits(const ASTContext &Context);
2961
2962 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2963 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2964 getSizeModifier(), getIndexTypeCVRQualifiers());
2965 }
2966
2967 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2968 QualType ET, const llvm::APInt &ArraySize,
2969 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2970 unsigned TypeQuals);
2971
2972 static bool classof(const Type *T) {
2973 return T->getTypeClass() == ConstantArray;
2974 }
2975};
2976
2977/// Represents a C array with an unspecified size. For example 'int A[]' has
2978/// an IncompleteArrayType where the element type is 'int' and the size is
2979/// unspecified.
2980class IncompleteArrayType : public ArrayType {
2981 friend class ASTContext; // ASTContext creates these.
2982
2983 IncompleteArrayType(QualType et, QualType can,
2984 ArraySizeModifier sm, unsigned tq)
2985 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2986
2987public:
2988 friend class StmtIteratorBase;
2989
2990 bool isSugared() const { return false; }
2991 QualType desugar() const { return QualType(this, 0); }
2992
2993 static bool classof(const Type *T) {
2994 return T->getTypeClass() == IncompleteArray;
2995 }
2996
2997 void Profile(llvm::FoldingSetNodeID &ID) {
2998 Profile(ID, getElementType(), getSizeModifier(),
2999 getIndexTypeCVRQualifiers());
3000 }
3001
3002 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3003 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3004 ID.AddPointer(ET.getAsOpaquePtr());
3005 ID.AddInteger(SizeMod);
3006 ID.AddInteger(TypeQuals);
3007 }
3008};
3009
3010/// Represents a C array with a specified size that is not an
3011/// integer-constant-expression. For example, 'int s[x+foo()]'.
3012/// Since the size expression is an arbitrary expression, we store it as such.
3013///
3014/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3015/// should not be: two lexically equivalent variable array types could mean
3016/// different things, for example, these variables do not have the same type
3017/// dynamically:
3018///
3019/// void foo(int x) {
3020/// int Y[x];
3021/// ++x;
3022/// int Z[x];
3023/// }
3024class VariableArrayType : public ArrayType {
3025 friend class ASTContext; // ASTContext creates these.
3026
3027 /// An assignment-expression. VLA's are only permitted within
3028 /// a function block.
3029 Stmt *SizeExpr;
3030
3031 /// The range spanned by the left and right array brackets.
3032 SourceRange Brackets;
3033
3034 VariableArrayType(QualType et, QualType can, Expr *e,
3035 ArraySizeModifier sm, unsigned tq,
3036 SourceRange brackets)
3037 : ArrayType(VariableArray, et, can, sm, tq, e),
3038 SizeExpr((Stmt*) e), Brackets(brackets) {}
3039
3040public:
3041 friend class StmtIteratorBase;
3042
3043 Expr *getSizeExpr() const {
3044 // We use C-style casts instead of cast<> here because we do not wish
3045 // to have a dependency of Type.h on Stmt.h/Expr.h.
3046 return (Expr*) SizeExpr;
3047 }
3048
3049 SourceRange getBracketsRange() const { return Brackets; }
3050 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3051 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3052
3053 bool isSugared() const { return false; }
3054 QualType desugar() const { return QualType(this, 0); }
3055
3056 static bool classof(const Type *T) {
3057 return T->getTypeClass() == VariableArray;
3058 }
3059
3060 void Profile(llvm::FoldingSetNodeID &ID) {
3061 llvm_unreachable("Cannot unique VariableArrayTypes.");
3062 }
3063};
3064
3065/// Represents an array type in C++ whose size is a value-dependent expression.
3066///
3067/// For example:
3068/// \code
3069/// template<typename T, int Size>
3070/// class array {
3071/// T data[Size];
3072/// };
3073/// \endcode
3074///
3075/// For these types, we won't actually know what the array bound is
3076/// until template instantiation occurs, at which point this will
3077/// become either a ConstantArrayType or a VariableArrayType.
3078class DependentSizedArrayType : public ArrayType {
3079 friend class ASTContext; // ASTContext creates these.
3080
3081 const ASTContext &Context;
3082
3083 /// An assignment expression that will instantiate to the
3084 /// size of the array.
3085 ///
3086 /// The expression itself might be null, in which case the array
3087 /// type will have its size deduced from an initializer.
3088 Stmt *SizeExpr;
3089
3090 /// The range spanned by the left and right array brackets.
3091 SourceRange Brackets;
3092
3093 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3094 Expr *e, ArraySizeModifier sm, unsigned tq,
3095 SourceRange brackets);
3096
3097public:
3098 friend class StmtIteratorBase;
3099
3100 Expr *getSizeExpr() const {
3101 // We use C-style casts instead of cast<> here because we do not wish
3102 // to have a dependency of Type.h on Stmt.h/Expr.h.
3103 return (Expr*) SizeExpr;
3104 }
3105
3106 SourceRange getBracketsRange() const { return Brackets; }
3107 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3108 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3109
3110 bool isSugared() const { return false; }
3111 QualType desugar() const { return QualType(this, 0); }
3112
3113 static bool classof(const Type *T) {
3114 return T->getTypeClass() == DependentSizedArray;
3115 }
3116
3117 void Profile(llvm::FoldingSetNodeID &ID) {
3118 Profile(ID, Context, getElementType(),
3119 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3120 }
3121
3122 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3123 QualType ET, ArraySizeModifier SizeMod,
3124 unsigned TypeQuals, Expr *E);
3125};
3126
3127/// Represents an extended address space qualifier where the input address space
3128/// value is dependent. Non-dependent address spaces are not represented with a
3129/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3130///
3131/// For example:
3132/// \code
3133/// template<typename T, int AddrSpace>
3134/// class AddressSpace {
3135/// typedef T __attribute__((address_space(AddrSpace))) type;
3136/// }
3137/// \endcode
3138class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3139 friend class ASTContext;
3140
3141 const ASTContext &Context;
3142 Expr *AddrSpaceExpr;
3143 QualType PointeeType;
3144 SourceLocation loc;
3145
3146 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3147 QualType can, Expr *AddrSpaceExpr,
3148 SourceLocation loc);
3149
3150public:
3151 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3152 QualType getPointeeType() const { return PointeeType; }
3153 SourceLocation getAttributeLoc() const { return loc; }
3154
3155 bool isSugared() const { return false; }
3156 QualType desugar() const { return QualType(this, 0); }
3157
3158 static bool classof(const Type *T) {
3159 return T->getTypeClass() == DependentAddressSpace;
3160 }
3161
3162 void Profile(llvm::FoldingSetNodeID &ID) {
3163 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3164 }
3165
3166 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3167 QualType PointeeType, Expr *AddrSpaceExpr);
3168};
3169
3170/// Represents an extended vector type where either the type or size is
3171/// dependent.
3172///
3173/// For example:
3174/// \code
3175/// template<typename T, int Size>
3176/// class vector {
3177/// typedef T __attribute__((ext_vector_type(Size))) type;
3178/// }
3179/// \endcode
3180class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3181 friend class ASTContext;
3182
3183 const ASTContext &Context;
3184 Expr *SizeExpr;
3185
3186 /// The element type of the array.
3187 QualType ElementType;
3188
3189 SourceLocation loc;
3190
3191 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3192 QualType can, Expr *SizeExpr, SourceLocation loc);
3193
3194public:
3195 Expr *getSizeExpr() const { return SizeExpr; }
3196 QualType getElementType() const { return ElementType; }
3197 SourceLocation getAttributeLoc() const { return loc; }
3198
3199 bool isSugared() const { return false; }
3200 QualType desugar() const { return QualType(this, 0); }
3201
3202 static bool classof(const Type *T) {
3203 return T->getTypeClass() == DependentSizedExtVector;
3204 }
3205
3206 void Profile(llvm::FoldingSetNodeID &ID) {
3207 Profile(ID, Context, getElementType(), getSizeExpr());
3208 }
3209
3210 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3211 QualType ElementType, Expr *SizeExpr);
3212};
3213
3214
3215/// Represents a GCC generic vector type. This type is created using
3216/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3217/// bytes; or from an Altivec __vector or vector declaration.
3218/// Since the constructor takes the number of vector elements, the
3219/// client is responsible for converting the size into the number of elements.
3220class VectorType : public Type, public llvm::FoldingSetNode {
3221public:
3222 enum VectorKind {
3223 /// not a target-specific vector type
3224 GenericVector,
3225
3226 /// is AltiVec vector
3227 AltiVecVector,
3228
3229 /// is AltiVec 'vector Pixel'
3230 AltiVecPixel,
3231
3232 /// is AltiVec 'vector bool ...'
3233 AltiVecBool,
3234
3235 /// is ARM Neon vector
3236 NeonVector,
3237
3238 /// is ARM Neon polynomial vector
3239 NeonPolyVector,
3240
3241 /// is AArch64 SVE fixed-length data vector
3242 SveFixedLengthDataVector,
3243
3244 /// is AArch64 SVE fixed-length predicate vector
3245 SveFixedLengthPredicateVector
3246 };
3247
3248protected:
3249 friend class ASTContext; // ASTContext creates these.
3250
3251 /// The element type of the vector.
3252 QualType ElementType;
3253
3254 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3255 VectorKind vecKind);
3256
3257 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3258 QualType canonType, VectorKind vecKind);
3259
3260public:
3261 QualType getElementType() const { return ElementType; }
3262 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3263
3264 bool isSugared() const { return false; }
3265 QualType desugar() const { return QualType(this, 0); }
3266
3267 VectorKind getVectorKind() const {
3268 return VectorKind(VectorTypeBits.VecKind);
3269 }
3270
3271 void Profile(llvm::FoldingSetNodeID &ID) {
3272 Profile(ID, getElementType(), getNumElements(),
3273 getTypeClass(), getVectorKind());
3274 }
3275
3276 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3277 unsigned NumElements, TypeClass TypeClass,
3278 VectorKind VecKind) {
3279 ID.AddPointer(ElementType.getAsOpaquePtr());
3280 ID.AddInteger(NumElements);
3281 ID.AddInteger(TypeClass);
3282 ID.AddInteger(VecKind);
3283 }
3284
3285 static bool classof(const Type *T) {
3286 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3287 }
3288};
3289
3290/// Represents a vector type where either the type or size is dependent.
3291////
3292/// For example:
3293/// \code
3294/// template<typename T, int Size>
3295/// class vector {
3296/// typedef T __attribute__((vector_size(Size))) type;
3297/// }
3298/// \endcode
3299class DependentVectorType : public Type, public llvm::FoldingSetNode {
3300 friend class ASTContext;
3301
3302 const ASTContext &Context;
3303 QualType ElementType;
3304 Expr *SizeExpr;
3305 SourceLocation Loc;
3306
3307 DependentVectorType(const ASTContext &Context, QualType ElementType,
3308 QualType CanonType, Expr *SizeExpr,
3309 SourceLocation Loc, VectorType::VectorKind vecKind);
3310
3311public:
3312 Expr *getSizeExpr() const { return SizeExpr; }
3313 QualType getElementType() const { return ElementType; }
3314 SourceLocation getAttributeLoc() const { return Loc; }
3315 VectorType::VectorKind getVectorKind() const {
3316 return VectorType::VectorKind(VectorTypeBits.VecKind);
3317 }
3318
3319 bool isSugared() const { return false; }
3320 QualType desugar() const { return QualType(this, 0); }
3321
3322 static bool classof(const Type *T) {
3323 return T->getTypeClass() == DependentVector;
3324 }
3325
3326 void Profile(llvm::FoldingSetNodeID &ID) {
3327 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3328 }
3329
3330 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3331 QualType ElementType, const Expr *SizeExpr,
3332 VectorType::VectorKind VecKind);
3333};
3334
3335/// ExtVectorType - Extended vector type. This type is created using
3336/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3337/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3338/// class enables syntactic extensions, like Vector Components for accessing
3339/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3340/// Shading Language).
3341class ExtVectorType : public VectorType {
3342 friend class ASTContext; // ASTContext creates these.
3343
3344 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3345 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3346
3347public:
3348 static int getPointAccessorIdx(char c) {
3349 switch (c) {
3350 default: return -1;
3351 case 'x': case 'r': return 0;
3352 case 'y': case 'g': return 1;
3353 case 'z': case 'b': return 2;
3354 case 'w': case 'a': return 3;
3355 }
3356 }
3357
3358 static int getNumericAccessorIdx(char c) {
3359 switch (c) {
3360 default: return -1;
3361 case '0': return 0;
3362 case '1': return 1;
3363 case '2': return 2;
3364 case '3': return 3;
3365 case '4': return 4;
3366 case '5': return 5;
3367 case '6': return 6;
3368 case '7': return 7;
3369 case '8': return 8;
3370 case '9': return 9;
3371 case 'A':
3372 case 'a': return 10;
3373 case 'B':
3374 case 'b': return 11;
3375 case 'C':
3376 case 'c': return 12;
3377 case 'D':
3378 case 'd': return 13;
3379 case 'E':
3380 case 'e': return 14;
3381 case 'F':
3382 case 'f': return 15;
3383 }
3384 }
3385
3386 static int getAccessorIdx(char c, bool isNumericAccessor) {
3387 if (isNumericAccessor)
3388 return getNumericAccessorIdx(c);
3389 else
3390 return getPointAccessorIdx(c);
3391 }
3392
3393 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3394 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3395 return unsigned(idx-1) < getNumElements();
3396 return false;
3397 }
3398
3399 bool isSugared() const { return false; }
3400 QualType desugar() const { return QualType(this, 0); }
3401
3402 static bool classof(const Type *T) {
3403 return T->getTypeClass() == ExtVector;
3404 }
3405};
3406
3407/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3408/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3409/// number of rows and "columns" specifies the number of columns.
3410class MatrixType : public Type, public llvm::FoldingSetNode {
3411protected:
3412 friend class ASTContext;
3413
3414 /// The element type of the matrix.
3415 QualType ElementType;
3416
3417 MatrixType(QualType ElementTy, QualType CanonElementTy);
3418
3419 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3420 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3421
3422public:
3423 /// Returns type of the elements being stored in the matrix
3424 QualType getElementType() const { return ElementType; }
3425
3426 /// Valid elements types are the following:
3427 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3428 /// and _Bool
3429 /// * the standard floating types float or double
3430 /// * a half-precision floating point type, if one is supported on the target
3431 static bool isValidElementType(QualType T) {
3432 return T->isDependentType() ||
3433 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3434 }
3435
3436 bool isSugared() const { return false; }
3437 QualType desugar() const { return QualType(this, 0); }
3438
3439 static bool classof(const Type *T) {
3440 return T->getTypeClass() == ConstantMatrix ||
3441 T->getTypeClass() == DependentSizedMatrix;
3442 }
3443};
3444
3445/// Represents a concrete matrix type with constant number of rows and columns
3446class ConstantMatrixType final : public MatrixType {
3447protected:
3448 friend class ASTContext;
3449
3450 /// The element type of the matrix.
3451 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3452 QualType ElementType;
3453
3454 /// Number of rows and columns.
3455 unsigned NumRows;
3456 unsigned NumColumns;
3457
3458 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3459
3460 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3461 unsigned NColumns, QualType CanonElementType);
3462
3463 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3464 unsigned NColumns, QualType CanonElementType);
3465
3466public:
3467 /// Returns the number of rows in the matrix.
3468 unsigned getNumRows() const { return NumRows; }
3469
3470 /// Returns the number of columns in the matrix.
3471 unsigned getNumColumns() const { return NumColumns; }
3472
3473 /// Returns the number of elements required to embed the matrix into a vector.
3474 unsigned getNumElementsFlattened() const {
3475 return getNumRows() * getNumColumns();
3476 }
3477
3478 /// Returns true if \p NumElements is a valid matrix dimension.
3479 static constexpr bool isDimensionValid(size_t NumElements) {
3480 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3481 }
3482
3483 /// Returns the maximum number of elements per dimension.
3484 static constexpr unsigned getMaxElementsPerDimension() {
3485 return MaxElementsPerDimension;
3486 }
3487
3488 void Profile(llvm::FoldingSetNodeID &ID) {
3489 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3490 getTypeClass());
3491 }
3492
3493 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3494 unsigned NumRows, unsigned NumColumns,
3495 TypeClass TypeClass) {
3496 ID.AddPointer(ElementType.getAsOpaquePtr());
3497 ID.AddInteger(NumRows);
3498 ID.AddInteger(NumColumns);
3499 ID.AddInteger(TypeClass);
3500 }
3501
3502 static bool classof(const Type *T) {
3503 return T->getTypeClass() == ConstantMatrix;
3504 }
3505};
3506
3507/// Represents a matrix type where the type and the number of rows and columns
3508/// is dependent on a template.
3509class DependentSizedMatrixType final : public MatrixType {
3510 friend class ASTContext;
3511
3512 const ASTContext &Context;
3513 Expr *RowExpr;
3514 Expr *ColumnExpr;
3515
3516 SourceLocation loc;
3517
3518 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3519 QualType CanonicalType, Expr *RowExpr,
3520 Expr *ColumnExpr, SourceLocation loc);
3521
3522public:
3523 QualType getElementType() const { return ElementType; }
3524 Expr *getRowExpr() const { return RowExpr; }
3525 Expr *getColumnExpr() const { return ColumnExpr; }
3526 SourceLocation getAttributeLoc() const { return loc; }
3527
3528 bool isSugared() const { return false; }
3529 QualType desugar() const { return QualType(this, 0); }
3530
3531 static bool classof(const Type *T) {
3532 return T->getTypeClass() == DependentSizedMatrix;
3533 }
3534
3535 void Profile(llvm::FoldingSetNodeID &ID) {
3536 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3537 }
3538
3539 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3540 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3541};
3542
3543/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3544/// class of FunctionNoProtoType and FunctionProtoType.
3545class FunctionType : public Type {
3546 // The type returned by the function.
3547 QualType ResultType;
3548
3549public:
3550 /// Interesting information about a specific parameter that can't simply
3551 /// be reflected in parameter's type. This is only used by FunctionProtoType
3552 /// but is in FunctionType to make this class available during the
3553 /// specification of the bases of FunctionProtoType.
3554 ///
3555 /// It makes sense to model language features this way when there's some
3556 /// sort of parameter-specific override (such as an attribute) that
3557 /// affects how the function is called. For example, the ARC ns_consumed
3558 /// attribute changes whether a parameter is passed at +0 (the default)
3559 /// or +1 (ns_consumed). This must be reflected in the function type,
3560 /// but isn't really a change to the parameter type.
3561 ///
3562 /// One serious disadvantage of modelling language features this way is
3563 /// that they generally do not work with language features that attempt
3564 /// to destructure types. For example, template argument deduction will
3565 /// not be able to match a parameter declared as
3566 /// T (*)(U)
3567 /// against an argument of type
3568 /// void (*)(__attribute__((ns_consumed)) id)
3569 /// because the substitution of T=void, U=id into the former will
3570 /// not produce the latter.
3571 class ExtParameterInfo {
3572 enum {
3573 ABIMask = 0x0F,
3574 IsConsumed = 0x10,
3575 HasPassObjSize = 0x20,
3576 IsNoEscape = 0x40,
3577 };
3578 unsigned char Data = 0;
3579
3580 public:
3581 ExtParameterInfo() = default;
3582
3583 /// Return the ABI treatment of this parameter.
3584 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3585 ExtParameterInfo withABI(ParameterABI kind) const {
3586 ExtParameterInfo copy = *this;
3587 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3588 return copy;
3589 }
3590
3591 /// Is this parameter considered "consumed" by Objective-C ARC?
3592 /// Consumed parameters must have retainable object type.
3593 bool isConsumed() const { return (Data & IsConsumed); }
3594 ExtParameterInfo withIsConsumed(bool consumed) const {
3595 ExtParameterInfo copy = *this;
3596 if (consumed)
3597 copy.Data |= IsConsumed;
3598 else
3599 copy.Data &= ~IsConsumed;
3600 return copy;
3601 }
3602
3603 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3604 ExtParameterInfo withHasPassObjectSize() const {
3605 ExtParameterInfo Copy = *this;
3606 Copy.Data |= HasPassObjSize;
3607 return Copy;
3608 }
3609
3610 bool isNoEscape() const { return Data & IsNoEscape; }
3611 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3612 ExtParameterInfo Copy = *this;
3613 if (NoEscape)
3614 Copy.Data |= IsNoEscape;
3615 else
3616 Copy.Data &= ~IsNoEscape;
3617 return Copy;
3618 }
3619
3620 unsigned char getOpaqueValue() const { return Data; }
3621 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3622 ExtParameterInfo result;
3623 result.Data = data;
3624 return result;
3625 }
3626
3627 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3628 return lhs.Data == rhs.Data;
3629 }
3630
3631 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3632 return lhs.Data != rhs.Data;
3633 }
3634 };
3635
3636 /// A class which abstracts out some details necessary for
3637 /// making a call.
3638 ///
3639 /// It is not actually used directly for storing this information in
3640 /// a FunctionType, although FunctionType does currently use the
3641 /// same bit-pattern.
3642 ///
3643 // If you add a field (say Foo), other than the obvious places (both,
3644 // constructors, compile failures), what you need to update is
3645 // * Operator==
3646 // * getFoo
3647 // * withFoo
3648 // * functionType. Add Foo, getFoo.
3649 // * ASTContext::getFooType
3650 // * ASTContext::mergeFunctionTypes
3651 // * FunctionNoProtoType::Profile
3652 // * FunctionProtoType::Profile
3653 // * TypePrinter::PrintFunctionProto
3654 // * AST read and write
3655 // * Codegen
3656 class ExtInfo {
3657 friend class FunctionType;
3658
3659 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3660 // adjust the Bits field below, and if you add bits, you'll need to adjust
3661 // Type::FunctionTypeBitfields::ExtInfo as well.
3662
3663 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3664 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3665 //
3666 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3667 enum { CallConvMask = 0x1F };
3668 enum { NoReturnMask = 0x20 };
3669 enum {