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