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