clang  10.0.0svn
Type.h
Go to the documentation of this file.
1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// C Language Family Type Representation
11 ///
12 /// This file defines the clang::Type interface and subclasses, used to
13 /// represent types for languages in the C family.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #ifndef LLVM_CLANG_AST_TYPE_H
18 #define LLVM_CLANG_AST_TYPE_H
19 
21 #include "clang/AST/TemplateName.h"
23 #include "clang/Basic/AttrKinds.h"
24 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/Linkage.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/Visibility.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/APSInt.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/PointerLikeTypeTraits.h"
47 #include "llvm/Support/type_traits.h"
48 #include "llvm/Support/TrailingObjects.h"
49 #include <cassert>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <string>
54 #include <type_traits>
55 #include <utility>
56 
57 namespace clang {
58 
59 class ExtQuals;
60 class QualType;
61 class TagDecl;
62 class Type;
63 
64 enum {
67 };
68 
69 } // namespace clang
70 
71 namespace llvm {
72 
73  template <typename T>
74  struct PointerLikeTypeTraits;
75  template<>
77  static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78 
80  return static_cast< ::clang::Type*>(P);
81  }
82 
83  enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84  };
85 
86  template<>
88  static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89 
90  static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91  return static_cast< ::clang::ExtQuals*>(P);
92  }
93 
94  enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95  };
96 
97 } // namespace llvm
98 
99 namespace clang {
100 
101 class ASTContext;
102 template <typename> class CanQual;
103 class CXXRecordDecl;
104 class DeclContext;
105 class EnumDecl;
106 class Expr;
107 class ExtQualsTypeCommonBase;
108 class FunctionDecl;
109 class IdentifierInfo;
110 class NamedDecl;
111 class ObjCInterfaceDecl;
112 class ObjCProtocolDecl;
113 class ObjCTypeParamDecl;
114 struct PrintingPolicy;
115 class RecordDecl;
116 class Stmt;
117 class TagDecl;
118 class TemplateArgument;
119 class TemplateArgumentListInfo;
120 class TemplateArgumentLoc;
121 class TemplateTypeParmDecl;
122 class TypedefNameDecl;
123 class UnresolvedUsingTypenameDecl;
124 
125 using CanQualType = CanQual<Type>;
126 
127 // Provide forward declarations for all of the *Type classes.
128 #define TYPE(Class, Base) class Class##Type;
129 #include "clang/AST/TypeNodes.def"
130 
131 /// The collection of all-type qualifiers we support.
132 /// Clang supports five independent qualifiers:
133 /// * C99: const, volatile, and restrict
134 /// * MS: __unaligned
135 /// * Embedded C (TR18037): address spaces
136 /// * Objective C: the GC attributes (none, weak, or strong)
137 class Qualifiers {
138 public:
139  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140  Const = 0x1,
141  Restrict = 0x2,
142  Volatile = 0x4,
143  CVRMask = Const | Volatile | Restrict
144  };
145 
146  enum GC {
147  GCNone = 0,
149  Strong
150  };
151 
153  /// There is no lifetime qualification on this type.
155 
156  /// This object can be modified without requiring retains or
157  /// releases.
159 
160  /// Assigning into this object requires the old value to be
161  /// released and the new value to be retained. The timing of the
162  /// release of the old value is inexact: it may be moved to
163  /// immediately after the last known point where the value is
164  /// live.
166 
167  /// Reading or writing from this object requires a barrier call.
169 
170  /// Assigning into this object requires a lifetime extension.
171  OCL_Autoreleasing
172  };
173 
174  enum {
175  /// The maximum supported address space number.
176  /// 23 bits should be enough for anyone.
177  MaxAddressSpace = 0x7fffffu,
178 
179  /// The width of the "fast" qualifier mask.
180  FastWidth = 3,
181 
182  /// The fast qualifier mask.
183  FastMask = (1 << FastWidth) - 1
184  };
185 
186  /// Returns the common set of qualifiers while removing them from
187  /// the given sets.
189  // If both are only CVR-qualified, bit operations are sufficient.
190  if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191  Qualifiers Q;
192  Q.Mask = L.Mask & R.Mask;
193  L.Mask &= ~Q.Mask;
194  R.Mask &= ~Q.Mask;
195  return Q;
196  }
197 
198  Qualifiers Q;
199  unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200  Q.addCVRQualifiers(CommonCRV);
201  L.removeCVRQualifiers(CommonCRV);
202  R.removeCVRQualifiers(CommonCRV);
203 
204  if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
206  L.removeObjCGCAttr();
207  R.removeObjCGCAttr();
208  }
209 
210  if (L.getObjCLifetime() == R.getObjCLifetime()) {
212  L.removeObjCLifetime();
213  R.removeObjCLifetime();
214  }
215 
216  if (L.getAddressSpace() == R.getAddressSpace()) {
218  L.removeAddressSpace();
219  R.removeAddressSpace();
220  }
221  return Q;
222  }
223 
224  static Qualifiers fromFastMask(unsigned Mask) {
225  Qualifiers Qs;
226  Qs.addFastQualifiers(Mask);
227  return Qs;
228  }
229 
230  static Qualifiers fromCVRMask(unsigned CVR) {
231  Qualifiers Qs;
232  Qs.addCVRQualifiers(CVR);
233  return Qs;
234  }
235 
236  static Qualifiers fromCVRUMask(unsigned CVRU) {
237  Qualifiers Qs;
238  Qs.addCVRUQualifiers(CVRU);
239  return Qs;
240  }
241 
242  // Deserialize qualifiers from an opaque representation.
243  static Qualifiers fromOpaqueValue(unsigned opaque) {
244  Qualifiers Qs;
245  Qs.Mask = opaque;
246  return Qs;
247  }
248 
249  // Serialize these qualifiers into an opaque representation.
250  unsigned getAsOpaqueValue() const {
251  return Mask;
252  }
253 
254  bool hasConst() const { return Mask & Const; }
255  bool hasOnlyConst() const { return Mask == Const; }
256  void removeConst() { Mask &= ~Const; }
257  void addConst() { Mask |= Const; }
258 
259  bool hasVolatile() const { return Mask & Volatile; }
260  bool hasOnlyVolatile() const { return Mask == Volatile; }
261  void removeVolatile() { Mask &= ~Volatile; }
262  void addVolatile() { Mask |= Volatile; }
263 
264  bool hasRestrict() const { return Mask & Restrict; }
265  bool hasOnlyRestrict() const { return Mask == Restrict; }
266  void removeRestrict() { Mask &= ~Restrict; }
267  void addRestrict() { Mask |= Restrict; }
268 
269  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271  unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272 
273  void setCVRQualifiers(unsigned mask) {
274  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
275  Mask = (Mask & ~CVRMask) | mask;
276  }
277  void removeCVRQualifiers(unsigned mask) {
278  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
279  Mask &= ~mask;
280  }
282  removeCVRQualifiers(CVRMask);
283  }
284  void addCVRQualifiers(unsigned mask) {
285  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
286  Mask |= mask;
287  }
288  void addCVRUQualifiers(unsigned mask) {
289  assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
290  Mask |= mask;
291  }
292 
293  bool hasUnaligned() const { return Mask & UMask; }
294  void setUnaligned(bool flag) {
295  Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296  }
297  void removeUnaligned() { Mask &= ~UMask; }
298  void addUnaligned() { Mask |= UMask; }
299 
300  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
303  Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304  }
305  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
307  assert(type);
308  setObjCGCAttr(type);
309  }
311  Qualifiers qs = *this;
312  qs.removeObjCGCAttr();
313  return qs;
314  }
316  Qualifiers qs = *this;
317  qs.removeObjCLifetime();
318  return qs;
319  }
321  Qualifiers qs = *this;
322  qs.removeAddressSpace();
323  return qs;
324  }
325 
326  bool hasObjCLifetime() const { return Mask & LifetimeMask; }
328  return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329  }
331  Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332  }
333  void removeObjCLifetime() { setObjCLifetime(OCL_None); }
335  assert(type);
336  assert(!hasObjCLifetime());
337  Mask |= (type << LifetimeShift);
338  }
339 
340  /// True if the lifetime is neither None or ExplicitNone.
342  ObjCLifetime lifetime = getObjCLifetime();
343  return (lifetime > OCL_ExplicitNone);
344  }
345 
346  /// True if the lifetime is either strong or weak.
348  ObjCLifetime lifetime = getObjCLifetime();
349  return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350  }
351 
352  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
354  return static_cast<LangAS>(Mask >> AddressSpaceShift);
355  }
357  return isTargetAddressSpace(getAddressSpace());
358  }
359  /// Get the address space attribute value to be printed by diagnostics.
361  auto Addr = getAddressSpace();
362  // This function is not supposed to be used with language specific
363  // address spaces. If that happens, the diagnostic message should consider
364  // printing the QualType instead of the address space value.
365  assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
366  if (Addr != LangAS::Default)
367  return toTargetAddressSpace(Addr);
368  // TODO: The diagnostic messages where Addr may be 0 should be fixed
369  // since it cannot differentiate the situation where 0 denotes the default
370  // address space or user specified __attribute__((address_space(0))).
371  return 0;
372  }
373  void setAddressSpace(LangAS space) {
374  assert((unsigned)space <= MaxAddressSpace);
375  Mask = (Mask & ~AddressSpaceMask)
376  | (((uint32_t) space) << AddressSpaceShift);
377  }
378  void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379  void addAddressSpace(LangAS space) {
380  assert(space != LangAS::Default);
381  setAddressSpace(space);
382  }
383 
384  // Fast qualifiers are those that can be allocated directly
385  // on a QualType object.
386  bool hasFastQualifiers() const { return getFastQualifiers(); }
387  unsigned getFastQualifiers() const { return Mask & FastMask; }
388  void setFastQualifiers(unsigned mask) {
389  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
390  Mask = (Mask & ~FastMask) | mask;
391  }
392  void removeFastQualifiers(unsigned mask) {
393  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
394  Mask &= ~mask;
395  }
397  removeFastQualifiers(FastMask);
398  }
399  void addFastQualifiers(unsigned mask) {
400  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
401  Mask |= mask;
402  }
403 
404  /// Return true if the set contains any qualifiers which require an ExtQuals
405  /// node to be allocated.
406  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
408  Qualifiers Quals = *this;
409  Quals.setFastQualifiers(0);
410  return Quals;
411  }
412 
413  /// Return true if the set contains any qualifiers.
414  bool hasQualifiers() const { return Mask; }
415  bool empty() const { return !Mask; }
416 
417  /// Add the qualifiers from the given set to this set.
419  // If the other set doesn't have any non-boolean qualifiers, just
420  // bit-or it in.
421  if (!(Q.Mask & ~CVRMask))
422  Mask |= Q.Mask;
423  else {
424  Mask |= (Q.Mask & CVRMask);
425  if (Q.hasAddressSpace())
426  addAddressSpace(Q.getAddressSpace());
427  if (Q.hasObjCGCAttr())
428  addObjCGCAttr(Q.getObjCGCAttr());
429  if (Q.hasObjCLifetime())
430  addObjCLifetime(Q.getObjCLifetime());
431  }
432  }
433 
434  /// Remove the qualifiers from the given set from this set.
436  // If the other set doesn't have any non-boolean qualifiers, just
437  // bit-and the inverse in.
438  if (!(Q.Mask & ~CVRMask))
439  Mask &= ~Q.Mask;
440  else {
441  Mask &= ~(Q.Mask & CVRMask);
442  if (getObjCGCAttr() == Q.getObjCGCAttr())
443  removeObjCGCAttr();
444  if (getObjCLifetime() == Q.getObjCLifetime())
445  removeObjCLifetime();
446  if (getAddressSpace() == Q.getAddressSpace())
447  removeAddressSpace();
448  }
449  }
450 
451  /// Add the qualifiers from the given set to this set, given that
452  /// they don't conflict.
454  assert(getAddressSpace() == qs.getAddressSpace() ||
455  !hasAddressSpace() || !qs.hasAddressSpace());
456  assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
457  !hasObjCGCAttr() || !qs.hasObjCGCAttr());
458  assert(getObjCLifetime() == qs.getObjCLifetime() ||
459  !hasObjCLifetime() || !qs.hasObjCLifetime());
460  Mask |= qs.Mask;
461  }
462 
463  /// Returns true if address space A is equal to or a superset of B.
464  /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465  /// overlapping address spaces.
466  /// CL1.1 or CL1.2:
467  /// every address space is a superset of itself.
468  /// CL2.0 adds:
469  /// __generic is a superset of any address space except for __constant.
471  // Address spaces must match exactly.
472  return A == B ||
473  // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474  // for __constant can be used as __generic.
476  }
477 
478  /// Returns true if the address space in these qualifiers is equal to or
479  /// a superset of the address space in the argument qualifiers.
481  return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482  }
483 
484  /// Determines if these qualifiers compatibly include another set.
485  /// Generally this answers the question of whether an object with the other
486  /// qualifiers can be safely used as an object with these qualifiers.
487  bool compatiblyIncludes(Qualifiers other) const {
488  return isAddressSpaceSupersetOf(other) &&
489  // ObjC GC qualifiers can match, be added, or be removed, but can't
490  // be changed.
491  (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492  !other.hasObjCGCAttr()) &&
493  // ObjC lifetime qualifiers must match exactly.
494  getObjCLifetime() == other.getObjCLifetime() &&
495  // CVR qualifiers may subset.
496  (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497  // U qualifier may superset.
498  (!other.hasUnaligned() || hasUnaligned());
499  }
500 
501  /// Determines if these qualifiers compatibly include another set of
502  /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503  ///
504  /// One set of Objective-C lifetime qualifiers compatibly includes the other
505  /// if the lifetime qualifiers match, or if both are non-__weak and the
506  /// including set also contains the 'const' qualifier, or both are non-__weak
507  /// and one is None (which can only happen in non-ARC modes).
509  if (getObjCLifetime() == other.getObjCLifetime())
510  return true;
511 
512  if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513  return false;
514 
515  if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516  return true;
517 
518  return hasConst();
519  }
520 
521  /// Determine whether this set of qualifiers is a strict superset of
522  /// another set of qualifiers, not considering qualifier compatibility.
523  bool isStrictSupersetOf(Qualifiers Other) const;
524 
525  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527 
528  explicit operator bool() const { return hasQualifiers(); }
529 
531  addQualifiers(R);
532  return *this;
533  }
534 
535  // Union two qualifier sets. If an enumerated qualifier appears
536  // in both sets, use the one from the right.
538  L += R;
539  return L;
540  }
541 
543  removeQualifiers(R);
544  return *this;
545  }
546 
547  /// Compute the difference between two qualifier sets.
549  L -= R;
550  return L;
551  }
552 
553  std::string getAsString() const;
554  std::string getAsString(const PrintingPolicy &Policy) const;
555 
556  bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557  void print(raw_ostream &OS, const PrintingPolicy &Policy,
558  bool appendSpaceIfNonEmpty = false) const;
559 
560  void Profile(llvm::FoldingSetNodeID &ID) const {
561  ID.AddInteger(Mask);
562  }
563 
564 private:
565  // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566  // |C R V|U|GCAttr|Lifetime|AddressSpace|
567  uint32_t Mask = 0;
568 
569  static const uint32_t UMask = 0x8;
570  static const uint32_t UShift = 3;
571  static const uint32_t GCAttrMask = 0x30;
572  static const uint32_t GCAttrShift = 4;
573  static const uint32_t LifetimeMask = 0x1C0;
574  static const uint32_t LifetimeShift = 6;
575  static const uint32_t AddressSpaceMask =
576  ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577  static const uint32_t AddressSpaceShift = 9;
578 };
579 
580 /// A std::pair-like structure for storing a qualified type split
581 /// into its local qualifiers and its locally-unqualified type.
583  /// The locally-unqualified type.
584  const Type *Ty = nullptr;
585 
586  /// The local qualifiers.
588 
589  SplitQualType() = default;
590  SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591 
592  SplitQualType getSingleStepDesugaredType() const; // end of this file
593 
594  // Make std::tie work.
595  std::pair<const Type *,Qualifiers> asPair() const {
596  return std::pair<const Type *, Qualifiers>(Ty, Quals);
597  }
598 
600  return a.Ty == b.Ty && a.Quals == b.Quals;
601  }
603  return a.Ty != b.Ty || a.Quals != b.Quals;
604  }
605 };
606 
607 /// The kind of type we are substituting Objective-C type arguments into.
608 ///
609 /// The kind of substitution affects the replacement of type parameters when
610 /// no concrete type information is provided, e.g., when dealing with an
611 /// unspecialized type.
613  /// An ordinary type.
614  Ordinary,
615 
616  /// The result type of a method or function.
617  Result,
618 
619  /// The parameter type of a method or function.
620  Parameter,
621 
622  /// The type of a property.
623  Property,
624 
625  /// The superclass of a type.
626  Superclass,
627 };
628 
629 /// A (possibly-)qualified type.
630 ///
631 /// For efficiency, we don't store CV-qualified types as nodes on their
632 /// own: instead each reference to a type stores the qualifiers. This
633 /// greatly reduces the number of nodes we need to allocate for types (for
634 /// example we only need one for 'int', 'const int', 'volatile int',
635 /// 'const volatile int', etc).
636 ///
637 /// As an added efficiency bonus, instead of making this a pair, we
638 /// just store the two bits we care about in the low bits of the
639 /// pointer. To handle the packing/unpacking, we make QualType be a
640 /// simple wrapper class that acts like a smart pointer. A third bit
641 /// indicates whether there are extended qualifiers present, in which
642 /// case the pointer points to a special structure.
643 class QualType {
644  friend class QualifierCollector;
645 
646  // Thankfully, these are efficiently composable.
647  llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
649 
650  const ExtQuals *getExtQualsUnsafe() const {
651  return Value.getPointer().get<const ExtQuals*>();
652  }
653 
654  const Type *getTypePtrUnsafe() const {
655  return Value.getPointer().get<const Type*>();
656  }
657 
658  const ExtQualsTypeCommonBase *getCommonPtr() const {
659  assert(!isNull() && "Cannot retrieve a NULL type pointer");
660  auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661  CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662  return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663  }
664 
665 public:
666  QualType() = default;
667  QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668  QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669 
670  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672 
673  /// Retrieves a pointer to the underlying (unqualified) type.
674  ///
675  /// This function requires that the type not be NULL. If the type might be
676  /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677  const Type *getTypePtr() const;
678 
679  const Type *getTypePtrOrNull() const;
680 
681  /// Retrieves a pointer to the name of the base type.
682  const IdentifierInfo *getBaseTypeIdentifier() const;
683 
684  /// Divides a QualType into its unqualified type and a set of local
685  /// qualifiers.
686  SplitQualType split() const;
687 
688  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689 
690  static QualType getFromOpaquePtr(const void *Ptr) {
691  QualType T;
692  T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693  return T;
694  }
695 
696  const Type &operator*() const {
697  return *getTypePtr();
698  }
699 
700  const Type *operator->() const {
701  return getTypePtr();
702  }
703 
704  bool isCanonical() const;
705  bool isCanonicalAsParam() const;
706 
707  /// Return true if this QualType doesn't point to a type yet.
708  bool isNull() const {
709  return Value.getPointer().isNull();
710  }
711 
712  /// Determine whether this particular QualType instance has the
713  /// "const" qualifier set, without looking through typedefs that may have
714  /// added "const" at a different level.
715  bool isLocalConstQualified() const {
716  return (getLocalFastQualifiers() & Qualifiers::Const);
717  }
718 
719  /// Determine whether this type is const-qualified.
720  bool isConstQualified() const;
721 
722  /// Determine whether this particular QualType instance has the
723  /// "restrict" qualifier set, without looking through typedefs that may have
724  /// added "restrict" at a different level.
726  return (getLocalFastQualifiers() & Qualifiers::Restrict);
727  }
728 
729  /// Determine whether this type is restrict-qualified.
730  bool isRestrictQualified() const;
731 
732  /// Determine whether this particular QualType instance has the
733  /// "volatile" qualifier set, without looking through typedefs that may have
734  /// added "volatile" at a different level.
736  return (getLocalFastQualifiers() & Qualifiers::Volatile);
737  }
738 
739  /// Determine whether this type is volatile-qualified.
740  bool isVolatileQualified() const;
741 
742  /// Determine whether this particular QualType instance has any
743  /// qualifiers, without looking through any typedefs that might add
744  /// qualifiers at a different level.
745  bool hasLocalQualifiers() const {
746  return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747  }
748 
749  /// Determine whether this type has any qualifiers.
750  bool hasQualifiers() const;
751 
752  /// Determine whether this particular QualType instance has any
753  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754  /// instance.
756  return Value.getPointer().is<const ExtQuals*>();
757  }
758 
759  /// Retrieve the set of qualifiers local to this particular QualType
760  /// instance, not including any qualifiers acquired through typedefs or
761  /// other sugar.
762  Qualifiers getLocalQualifiers() const;
763 
764  /// Retrieve the set of qualifiers applied to this type.
765  Qualifiers getQualifiers() const;
766 
767  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768  /// local to this particular QualType instance, not including any qualifiers
769  /// acquired through typedefs or other sugar.
770  unsigned getLocalCVRQualifiers() const {
771  return getLocalFastQualifiers();
772  }
773 
774  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775  /// applied to this type.
776  unsigned getCVRQualifiers() const;
777 
778  bool isConstant(const ASTContext& Ctx) const {
779  return QualType::isConstant(*this, Ctx);
780  }
781 
782  /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783  bool isPODType(const ASTContext &Context) const;
784 
785  /// Return true if this is a POD type according to the rules of the C++98
786  /// standard, regardless of the current compilation's language.
787  bool isCXX98PODType(const ASTContext &Context) const;
788 
789  /// Return true if this is a POD type according to the more relaxed rules
790  /// of the C++11 standard, regardless of the current compilation's language.
791  /// (C++0x [basic.types]p9). Note that, unlike
792  /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793  bool isCXX11PODType(const ASTContext &Context) const;
794 
795  /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796  bool isTrivialType(const ASTContext &Context) const;
797 
798  /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799  bool isTriviallyCopyableType(const ASTContext &Context) const;
800 
801 
802  /// Returns true if it is a class and it might be dynamic.
803  bool mayBeDynamicClass() const;
804 
805  /// Returns true if it is not a class or if the class might not be dynamic.
806  bool mayBeNotDynamicClass() const;
807 
808  // Don't promise in the API that anything besides 'const' can be
809  // easily added.
810 
811  /// Add the `const` type qualifier to this QualType.
812  void addConst() {
813  addFastQualifiers(Qualifiers::Const);
814  }
815  QualType withConst() const {
816  return withFastQualifiers(Qualifiers::Const);
817  }
818 
819  /// Add the `volatile` type qualifier to this QualType.
820  void addVolatile() {
821  addFastQualifiers(Qualifiers::Volatile);
822  }
824  return withFastQualifiers(Qualifiers::Volatile);
825  }
826 
827  /// Add the `restrict` qualifier to this QualType.
828  void addRestrict() {
829  addFastQualifiers(Qualifiers::Restrict);
830  }
832  return withFastQualifiers(Qualifiers::Restrict);
833  }
834 
835  QualType withCVRQualifiers(unsigned CVR) const {
836  return withFastQualifiers(CVR);
837  }
838 
839  void addFastQualifiers(unsigned TQs) {
840  assert(!(TQs & ~Qualifiers::FastMask)
841  && "non-fast qualifier bits set in mask!");
842  Value.setInt(Value.getInt() | TQs);
843  }
844 
845  void removeLocalConst();
846  void removeLocalVolatile();
847  void removeLocalRestrict();
848  void removeLocalCVRQualifiers(unsigned Mask);
849 
850  void removeLocalFastQualifiers() { Value.setInt(0); }
851  void removeLocalFastQualifiers(unsigned Mask) {
852  assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
853  Value.setInt(Value.getInt() & ~Mask);
854  }
855 
856  // Creates a type with the given qualifiers in addition to any
857  // qualifiers already on this type.
858  QualType withFastQualifiers(unsigned TQs) const {
859  QualType T = *this;
860  T.addFastQualifiers(TQs);
861  return T;
862  }
863 
864  // Creates a type with exactly the given fast qualifiers, removing
865  // any existing fast qualifiers.
867  return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868  }
869 
870  // Removes fast qualifiers, but leaves any extended qualifiers in place.
872  QualType T = *this;
874  return T;
875  }
876 
877  QualType getCanonicalType() const;
878 
879  /// Return this type with all of the instance-specific qualifiers
880  /// removed, but without removing any qualifiers that may have been applied
881  /// through typedefs.
882  QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883 
884  /// Retrieve the unqualified variant of the given type,
885  /// removing as little sugar as possible.
886  ///
887  /// This routine looks through various kinds of sugar to find the
888  /// least-desugared type that is unqualified. For example, given:
889  ///
890  /// \code
891  /// typedef int Integer;
892  /// typedef const Integer CInteger;
893  /// typedef CInteger DifferenceType;
894  /// \endcode
895  ///
896  /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897  /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898  ///
899  /// The resulting type might still be qualified if it's sugar for an array
900  /// type. To strip qualifiers even from within a sugared array type, use
901  /// ASTContext::getUnqualifiedArrayType.
902  inline QualType getUnqualifiedType() const;
903 
904  /// Retrieve the unqualified variant of the given type, removing as little
905  /// sugar as possible.
906  ///
907  /// Like getUnqualifiedType(), but also returns the set of
908  /// qualifiers that were built up.
909  ///
910  /// The resulting type might still be qualified if it's sugar for an array
911  /// type. To strip qualifiers even from within a sugared array type, use
912  /// ASTContext::getUnqualifiedArrayType.
913  inline SplitQualType getSplitUnqualifiedType() const;
914 
915  /// Determine whether this type is more qualified than the other
916  /// given type, requiring exact equality for non-CVR qualifiers.
917  bool isMoreQualifiedThan(QualType Other) const;
918 
919  /// Determine whether this type is at least as qualified as the other
920  /// given type, requiring exact equality for non-CVR qualifiers.
921  bool isAtLeastAsQualifiedAs(QualType Other) const;
922 
923  QualType getNonReferenceType() const;
924 
925  /// Determine the type of a (typically non-lvalue) expression with the
926  /// specified result type.
927  ///
928  /// This routine should be used for expressions for which the return type is
929  /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930  /// an lvalue. It removes a top-level reference (since there are no
931  /// expressions of reference type) and deletes top-level cvr-qualifiers
932  /// from non-class types (in C++) or all types (in C).
933  QualType getNonLValueExprType(const ASTContext &Context) const;
934 
935  /// Return the specified type with any "sugar" removed from
936  /// the type. This takes off typedefs, typeof's etc. If the outer level of
937  /// the type is already concrete, it returns it unmodified. This is similar
938  /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940  /// concrete.
941  ///
942  /// Qualifiers are left in place.
943  QualType getDesugaredType(const ASTContext &Context) const {
944  return getDesugaredType(*this, Context);
945  }
946 
948  return getSplitDesugaredType(*this);
949  }
950 
951  /// Return the specified type with one level of "sugar" removed from
952  /// the type.
953  ///
954  /// This routine takes off the first typedef, typeof, etc. If the outer level
955  /// of the type is already concrete, it returns it unmodified.
957  return getSingleStepDesugaredTypeImpl(*this, Context);
958  }
959 
960  /// Returns the specified type after dropping any
961  /// outer-level parentheses.
963  if (isa<ParenType>(*this))
964  return QualType::IgnoreParens(*this);
965  return *this;
966  }
967 
968  /// Indicate whether the specified types and qualifiers are identical.
969  friend bool operator==(const QualType &LHS, const QualType &RHS) {
970  return LHS.Value == RHS.Value;
971  }
972  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973  return LHS.Value != RHS.Value;
974  }
975  friend bool operator<(const QualType &LHS, const QualType &RHS) {
976  return LHS.Value < RHS.Value;
977  }
978 
979  static std::string getAsString(SplitQualType split,
980  const PrintingPolicy &Policy) {
981  return getAsString(split.Ty, split.Quals, Policy);
982  }
983  static std::string getAsString(const Type *ty, Qualifiers qs,
984  const PrintingPolicy &Policy);
985 
986  std::string getAsString() const;
987  std::string getAsString(const PrintingPolicy &Policy) const;
988 
989  void print(raw_ostream &OS, const PrintingPolicy &Policy,
990  const Twine &PlaceHolder = Twine(),
991  unsigned Indentation = 0) const;
992 
993  static void print(SplitQualType split, raw_ostream &OS,
994  const PrintingPolicy &policy, const Twine &PlaceHolder,
995  unsigned Indentation = 0) {
996  return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997  }
998 
999  static void print(const Type *ty, Qualifiers qs,
1000  raw_ostream &OS, const PrintingPolicy &policy,
1001  const Twine &PlaceHolder,
1002  unsigned Indentation = 0);
1003 
1004  void getAsStringInternal(std::string &Str,
1005  const PrintingPolicy &Policy) const;
1006 
1007  static void getAsStringInternal(SplitQualType split, std::string &out,
1008  const PrintingPolicy &policy) {
1009  return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010  }
1011 
1012  static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013  std::string &out,
1014  const PrintingPolicy &policy);
1015 
1017  const QualType &T;
1018  const PrintingPolicy &Policy;
1019  const Twine &PlaceHolder;
1020  unsigned Indentation;
1021 
1022  public:
1024  const Twine &PlaceHolder, unsigned Indentation)
1025  : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026  Indentation(Indentation) {}
1027 
1028  friend raw_ostream &operator<<(raw_ostream &OS,
1029  const StreamedQualTypeHelper &SQT) {
1030  SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031  return OS;
1032  }
1033  };
1034 
1036  const Twine &PlaceHolder = Twine(),
1037  unsigned Indentation = 0) const {
1038  return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039  }
1040 
1041  void dump(const char *s) const;
1042  void dump() const;
1043  void dump(llvm::raw_ostream &OS) const;
1044 
1045  void Profile(llvm::FoldingSetNodeID &ID) const {
1046  ID.AddPointer(getAsOpaquePtr());
1047  }
1048 
1049  /// Return the address space of this type.
1050  inline LangAS getAddressSpace() const;
1051 
1052  /// Returns gc attribute of this type.
1053  inline Qualifiers::GC getObjCGCAttr() const;
1054 
1055  /// true when Type is objc's weak.
1056  bool isObjCGCWeak() const {
1057  return getObjCGCAttr() == Qualifiers::Weak;
1058  }
1059 
1060  /// true when Type is objc's strong.
1061  bool isObjCGCStrong() const {
1062  return getObjCGCAttr() == Qualifiers::Strong;
1063  }
1064 
1065  /// Returns lifetime attribute of this type.
1067  return getQualifiers().getObjCLifetime();
1068  }
1069 
1071  return getQualifiers().hasNonTrivialObjCLifetime();
1072  }
1073 
1075  return getQualifiers().hasStrongOrWeakObjCLifetime();
1076  }
1077 
1078  // true when Type is objc's weak and weak is enabled but ARC isn't.
1079  bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080 
1082  /// The type does not fall into any of the following categories. Note that
1083  /// this case is zero-valued so that values of this enum can be used as a
1084  /// boolean condition for non-triviality.
1086 
1087  /// The type is an Objective-C retainable pointer type that is qualified
1088  /// with the ARC __strong qualifier.
1090 
1091  /// The type is an Objective-C retainable pointer type that is qualified
1092  /// with the ARC __weak qualifier.
1094 
1095  /// The type is a struct containing a field whose type is not PCK_Trivial.
1096  PDIK_Struct
1097  };
1098 
1099  /// Functions to query basic properties of non-trivial C struct types.
1100 
1101  /// Check if this is a non-trivial type that would cause a C struct
1102  /// transitively containing this type to be non-trivial to default initialize
1103  /// and return the kind.
1105  isNonTrivialToPrimitiveDefaultInitialize() const;
1106 
1108  /// The type does not fall into any of the following categories. Note that
1109  /// this case is zero-valued so that values of this enum can be used as a
1110  /// boolean condition for non-triviality.
1112 
1113  /// The type would be trivial except that it is volatile-qualified. Types
1114  /// that fall into one of the other non-trivial cases may additionally be
1115  /// volatile-qualified.
1117 
1118  /// The type is an Objective-C retainable pointer type that is qualified
1119  /// with the ARC __strong qualifier.
1121 
1122  /// The type is an Objective-C retainable pointer type that is qualified
1123  /// with the ARC __weak qualifier.
1125 
1126  /// The type is a struct containing a field whose type is neither
1127  /// PCK_Trivial nor PCK_VolatileTrivial.
1128  /// Note that a C++ struct type does not necessarily match this; C++ copying
1129  /// semantics are too complex to express here, in part because they depend
1130  /// on the exact constructor or assignment operator that is chosen by
1131  /// overload resolution to do the copy.
1132  PCK_Struct
1133  };
1134 
1135  /// Check if this is a non-trivial type that would cause a C struct
1136  /// transitively containing this type to be non-trivial. This function can be
1137  /// used to determine whether a field of this type can be declared inside a C
1138  /// union.
1139  bool isNonTrivialPrimitiveCType(const ASTContext &Ctx) const;
1140 
1141  /// Check if this is a non-trivial type that would cause a C struct
1142  /// transitively containing this type to be non-trivial to copy and return the
1143  /// kind.
1144  PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1145 
1146  /// Check if this is a non-trivial type that would cause a C struct
1147  /// transitively containing this type to be non-trivial to destructively
1148  /// move and return the kind. Destructive move in this context is a C++-style
1149  /// move in which the source object is placed in a valid but unspecified state
1150  /// after it is moved, as opposed to a truly destructive move in which the
1151  /// source object is placed in an uninitialized state.
1152  PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1153 
1159  DK_nontrivial_c_struct
1160  };
1161 
1162  /// Returns a nonzero value if objects of this type require
1163  /// non-trivial work to clean up after. Non-zero because it's
1164  /// conceivable that qualifiers (objc_gc(weak)?) could make
1165  /// something require destruction.
1167  return isDestructedTypeImpl(*this);
1168  }
1169 
1170  /// Determine whether expressions of the given type are forbidden
1171  /// from being lvalues in C.
1172  ///
1173  /// The expression types that are forbidden to be lvalues are:
1174  /// - 'void', but not qualified void
1175  /// - function types
1176  ///
1177  /// The exact rule here is C99 6.3.2.1:
1178  /// An lvalue is an expression with an object type or an incomplete
1179  /// type other than void.
1180  bool isCForbiddenLValueType() const;
1181 
1182  /// Substitute type arguments for the Objective-C type parameters used in the
1183  /// subject type.
1184  ///
1185  /// \param ctx ASTContext in which the type exists.
1186  ///
1187  /// \param typeArgs The type arguments that will be substituted for the
1188  /// Objective-C type parameters in the subject type, which are generally
1189  /// computed via \c Type::getObjCSubstitutions. If empty, the type
1190  /// parameters will be replaced with their bounds or id/Class, as appropriate
1191  /// for the context.
1192  ///
1193  /// \param context The context in which the subject type was written.
1194  ///
1195  /// \returns the resulting type.
1196  QualType substObjCTypeArgs(ASTContext &ctx,
1197  ArrayRef<QualType> typeArgs,
1198  ObjCSubstitutionContext context) const;
1199 
1200  /// Substitute type arguments from an object type for the Objective-C type
1201  /// parameters used in the subject type.
1202  ///
1203  /// This operation combines the computation of type arguments for
1204  /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1205  /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1206  /// callers that need to perform a single substitution in isolation.
1207  ///
1208  /// \param objectType The type of the object whose member type we're
1209  /// substituting into. For example, this might be the receiver of a message
1210  /// or the base of a property access.
1211  ///
1212  /// \param dc The declaration context from which the subject type was
1213  /// retrieved, which indicates (for example) which type parameters should
1214  /// be substituted.
1215  ///
1216  /// \param context The context in which the subject type was written.
1217  ///
1218  /// \returns the subject type after replacing all of the Objective-C type
1219  /// parameters with their corresponding arguments.
1220  QualType substObjCMemberType(QualType objectType,
1221  const DeclContext *dc,
1222  ObjCSubstitutionContext context) const;
1223 
1224  /// Strip Objective-C "__kindof" types from the given type.
1225  QualType stripObjCKindOfType(const ASTContext &ctx) const;
1226 
1227  /// Remove all qualifiers including _Atomic.
1228  QualType getAtomicUnqualifiedType() const;
1229 
1230 private:
1231  // These methods are implemented in a separate translation unit;
1232  // "static"-ize them to avoid creating temporary QualTypes in the
1233  // caller.
1234  static bool isConstant(QualType T, const ASTContext& Ctx);
1235  static QualType getDesugaredType(QualType T, const ASTContext &Context);
1236  static SplitQualType getSplitDesugaredType(QualType T);
1237  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1238  static QualType getSingleStepDesugaredTypeImpl(QualType type,
1239  const ASTContext &C);
1240  static QualType IgnoreParens(QualType T);
1241  static DestructionKind isDestructedTypeImpl(QualType type);
1242 };
1243 
1244 } // namespace clang
1245 
1246 namespace llvm {
1247 
1248 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1249 /// to a specific Type class.
1250 template<> struct simplify_type< ::clang::QualType> {
1252 
1254  return Val.getTypePtr();
1255  }
1256 };
1257 
1258 // Teach SmallPtrSet that QualType is "basically a pointer".
1259 template<>
1260 struct PointerLikeTypeTraits<clang::QualType> {
1261  static inline void *getAsVoidPointer(clang::QualType P) {
1262  return P.getAsOpaquePtr();
1263  }
1264 
1265  static inline clang::QualType getFromVoidPointer(void *P) {
1267  }
1268 
1269  // Various qualifiers go in low bits.
1270  enum { NumLowBitsAvailable = 0 };
1271 };
1272 
1273 } // namespace llvm
1274 
1275 namespace clang {
1276 
1277 /// Base class that is common to both the \c ExtQuals and \c Type
1278 /// classes, which allows \c QualType to access the common fields between the
1279 /// two.
1281  friend class ExtQuals;
1282  friend class QualType;
1283  friend class Type;
1284 
1285  /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1286  /// a self-referential pointer (for \c Type).
1287  ///
1288  /// This pointer allows an efficient mapping from a QualType to its
1289  /// underlying type pointer.
1290  const Type *const BaseType;
1291 
1292  /// The canonical type of this type. A QualType.
1293  QualType CanonicalType;
1294 
1295  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1296  : BaseType(baseType), CanonicalType(canon) {}
1297 };
1298 
1299 /// We can encode up to four bits in the low bits of a
1300 /// type pointer, but there are many more type qualifiers that we want
1301 /// to be able to apply to an arbitrary type. Therefore we have this
1302 /// struct, intended to be heap-allocated and used by QualType to
1303 /// store qualifiers.
1304 ///
1305 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1306 /// in three low bits on the QualType pointer; a fourth bit records whether
1307 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1308 /// Objective-C GC attributes) are much more rare.
1309 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1310  // NOTE: changing the fast qualifiers should be straightforward as
1311  // long as you don't make 'const' non-fast.
1312  // 1. Qualifiers:
1313  // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1314  // Fast qualifiers must occupy the low-order bits.
1315  // b) Update Qualifiers::FastWidth and FastMask.
1316  // 2. QualType:
1317  // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1318  // b) Update remove{Volatile,Restrict}, defined near the end of
1319  // this header.
1320  // 3. ASTContext:
1321  // a) Update get{Volatile,Restrict}Type.
1322 
1323  /// The immutable set of qualifiers applied by this node. Always contains
1324  /// extended qualifiers.
1325  Qualifiers Quals;
1326 
1327  ExtQuals *this_() { return this; }
1328 
1329 public:
1330  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1331  : ExtQualsTypeCommonBase(baseType,
1332  canon.isNull() ? QualType(this_(), 0) : canon),
1333  Quals(quals) {
1334  assert(Quals.hasNonFastQualifiers()
1335  && "ExtQuals created with no fast qualifiers");
1336  assert(!Quals.hasFastQualifiers()
1337  && "ExtQuals created with fast qualifiers");
1338  }
1339 
1340  Qualifiers getQualifiers() const { return Quals; }
1341 
1342  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1343  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1344 
1345  bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1347  return Quals.getObjCLifetime();
1348  }
1349 
1350  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1351  LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1352 
1353  const Type *getBaseType() const { return BaseType; }
1354 
1355 public:
1356  void Profile(llvm::FoldingSetNodeID &ID) const {
1357  Profile(ID, getBaseType(), Quals);
1358  }
1359 
1360  static void Profile(llvm::FoldingSetNodeID &ID,
1361  const Type *BaseType,
1362  Qualifiers Quals) {
1363  assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1364  ID.AddPointer(BaseType);
1365  Quals.Profile(ID);
1366  }
1367 };
1368 
1369 /// The kind of C++11 ref-qualifier associated with a function type.
1370 /// This determines whether a member function's "this" object can be an
1371 /// lvalue, rvalue, or neither.
1373  /// No ref-qualifier was provided.
1374  RQ_None = 0,
1375 
1376  /// An lvalue ref-qualifier was provided (\c &).
1378 
1379  /// An rvalue ref-qualifier was provided (\c &&).
1381 };
1382 
1383 /// Which keyword(s) were used to create an AutoType.
1384 enum class AutoTypeKeyword {
1385  /// auto
1386  Auto,
1387 
1388  /// decltype(auto)
1389  DecltypeAuto,
1390 
1391  /// __auto_type (GNU extension)
1392  GNUAutoType
1393 };
1394 
1395 /// The base class of the type hierarchy.
1396 ///
1397 /// A central concept with types is that each type always has a canonical
1398 /// type. A canonical type is the type with any typedef names stripped out
1399 /// of it or the types it references. For example, consider:
1400 ///
1401 /// typedef int foo;
1402 /// typedef foo* bar;
1403 /// 'int *' 'foo *' 'bar'
1404 ///
1405 /// There will be a Type object created for 'int'. Since int is canonical, its
1406 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1407 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1408 /// there is a PointerType that represents 'int*', which, like 'int', is
1409 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1410 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1411 /// is also 'int*'.
1412 ///
1413 /// Non-canonical types are useful for emitting diagnostics, without losing
1414 /// information about typedefs being used. Canonical types are useful for type
1415 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1416 /// about whether something has a particular form (e.g. is a function type),
1417 /// because they implicitly, recursively, strip all typedefs out of a type.
1418 ///
1419 /// Types, once created, are immutable.
1420 ///
1421 class alignas(8) Type : public ExtQualsTypeCommonBase {
1422 public:
1423  enum TypeClass {
1424 #define TYPE(Class, Base) Class,
1425 #define LAST_TYPE(Class) TypeLast = Class,
1426 #define ABSTRACT_TYPE(Class, Base)
1427 #include "clang/AST/TypeNodes.def"
1428  TagFirst = Record, TagLast = Enum
1429  };
1430 
1431 private:
1432  /// Bitfields required by the Type class.
1433  class TypeBitfields {
1434  friend class Type;
1435  template <class T> friend class TypePropertyCache;
1436 
1437  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1438  unsigned TC : 8;
1439 
1440  /// Whether this type is a dependent type (C++ [temp.dep.type]).
1441  unsigned Dependent : 1;
1442 
1443  /// Whether this type somehow involves a template parameter, even
1444  /// if the resolution of the type does not depend on a template parameter.
1445  unsigned InstantiationDependent : 1;
1446 
1447  /// Whether this type is a variably-modified type (C99 6.7.5).
1448  unsigned VariablyModified : 1;
1449 
1450  /// Whether this type contains an unexpanded parameter pack
1451  /// (for C++11 variadic templates).
1452  unsigned ContainsUnexpandedParameterPack : 1;
1453 
1454  /// True if the cache (i.e. the bitfields here starting with
1455  /// 'Cache') is valid.
1456  mutable unsigned CacheValid : 1;
1457 
1458  /// Linkage of this type.
1459  mutable unsigned CachedLinkage : 3;
1460 
1461  /// Whether this type involves and local or unnamed types.
1462  mutable unsigned CachedLocalOrUnnamed : 1;
1463 
1464  /// Whether this type comes from an AST file.
1465  mutable unsigned FromAST : 1;
1466 
1467  bool isCacheValid() const {
1468  return CacheValid;
1469  }
1470 
1471  Linkage getLinkage() const {
1472  assert(isCacheValid() && "getting linkage from invalid cache");
1473  return static_cast<Linkage>(CachedLinkage);
1474  }
1475 
1476  bool hasLocalOrUnnamedType() const {
1477  assert(isCacheValid() && "getting linkage from invalid cache");
1478  return CachedLocalOrUnnamed;
1479  }
1480  };
1481  enum { NumTypeBits = 18 };
1482 
1483 protected:
1484  // These classes allow subclasses to somewhat cleanly pack bitfields
1485  // into Type.
1486 
1488  friend class ArrayType;
1489 
1490  unsigned : NumTypeBits;
1491 
1492  /// CVR qualifiers from declarations like
1493  /// 'int X[static restrict 4]'. For function parameters only.
1494  unsigned IndexTypeQuals : 3;
1495 
1496  /// Storage class qualifiers from declarations like
1497  /// 'int X[static restrict 4]'. For function parameters only.
1498  /// Actually an ArrayType::ArraySizeModifier.
1499  unsigned SizeModifier : 3;
1500  };
1501 
1503  friend class BuiltinType;
1504 
1505  unsigned : NumTypeBits;
1506 
1507  /// The kind (BuiltinType::Kind) of builtin type this is.
1508  unsigned Kind : 8;
1509  };
1510 
1511  /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1512  /// Only common bits are stored here. Additional uncommon bits are stored
1513  /// in a trailing object after FunctionProtoType.
1515  friend class FunctionProtoType;
1516  friend class FunctionType;
1517 
1518  unsigned : NumTypeBits;
1519 
1520  /// Extra information which affects how the function is called, like
1521  /// regparm and the calling convention.
1522  unsigned ExtInfo : 12;
1523 
1524  /// The ref-qualifier associated with a \c FunctionProtoType.
1525  ///
1526  /// This is a value of type \c RefQualifierKind.
1527  unsigned RefQualifier : 2;
1528 
1529  /// Used only by FunctionProtoType, put here to pack with the
1530  /// other bitfields.
1531  /// The qualifiers are part of FunctionProtoType because...
1532  ///
1533  /// C++ 8.3.5p4: The return type, the parameter type list and the
1534  /// cv-qualifier-seq, [...], are part of the function type.
1535  unsigned FastTypeQuals : Qualifiers::FastWidth;
1536  /// Whether this function has extended Qualifiers.
1537  unsigned HasExtQuals : 1;
1538 
1539  /// The number of parameters this function has, not counting '...'.
1540  /// According to [implimits] 8 bits should be enough here but this is
1541  /// somewhat easy to exceed with metaprogramming and so we would like to
1542  /// keep NumParams as wide as reasonably possible.
1543  unsigned NumParams : 16;
1544 
1545  /// The type of exception specification this function has.
1546  unsigned ExceptionSpecType : 4;
1547 
1548  /// Whether this function has extended parameter information.
1549  unsigned HasExtParameterInfos : 1;
1550 
1551  /// Whether the function is variadic.
1552  unsigned Variadic : 1;
1553 
1554  /// Whether this function has a trailing return type.
1555  unsigned HasTrailingReturn : 1;
1556  };
1557 
1559  friend class ObjCObjectType;
1560 
1561  unsigned : NumTypeBits;
1562 
1563  /// The number of type arguments stored directly on this object type.
1564  unsigned NumTypeArgs : 7;
1565 
1566  /// The number of protocols stored directly on this object type.
1567  unsigned NumProtocols : 6;
1568 
1569  /// Whether this is a "kindof" type.
1570  unsigned IsKindOf : 1;
1571  };
1572 
1574  friend class ReferenceType;
1575 
1576  unsigned : NumTypeBits;
1577 
1578  /// True if the type was originally spelled with an lvalue sigil.
1579  /// This is never true of rvalue references but can also be false
1580  /// on lvalue references because of C++0x [dcl.typedef]p9,
1581  /// as follows:
1582  ///
1583  /// typedef int &ref; // lvalue, spelled lvalue
1584  /// typedef int &&rvref; // rvalue
1585  /// ref &a; // lvalue, inner ref, spelled lvalue
1586  /// ref &&a; // lvalue, inner ref
1587  /// rvref &a; // lvalue, inner ref, spelled lvalue
1588  /// rvref &&a; // rvalue, inner ref
1589  unsigned SpelledAsLValue : 1;
1590 
1591  /// True if the inner type is a reference type. This only happens
1592  /// in non-canonical forms.
1593  unsigned InnerRef : 1;
1594  };
1595 
1597  friend class TypeWithKeyword;
1598 
1599  unsigned : NumTypeBits;
1600 
1601  /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1602  unsigned Keyword : 8;
1603  };
1604 
1605  enum { NumTypeWithKeywordBits = 8 };
1606 
1608  friend class ElaboratedType;
1609 
1610  unsigned : NumTypeBits;
1611  unsigned : NumTypeWithKeywordBits;
1612 
1613  /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1614  unsigned HasOwnedTagDecl : 1;
1615  };
1616 
1618  friend class VectorType;
1619  friend class DependentVectorType;
1620 
1621  unsigned : NumTypeBits;
1622 
1623  /// The kind of vector, either a generic vector type or some
1624  /// target-specific vector type such as for AltiVec or Neon.
1625  unsigned VecKind : 3;
1626 
1627  /// The number of elements in the vector.
1628  unsigned NumElements : 29 - NumTypeBits;
1629 
1630  enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1631  };
1632 
1634  friend class AttributedType;
1635 
1636  unsigned : NumTypeBits;
1637 
1638  /// An AttributedType::Kind
1639  unsigned AttrKind : 32 - NumTypeBits;
1640  };
1641 
1643  friend class AutoType;
1644 
1645  unsigned : NumTypeBits;
1646 
1647  /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1648  /// or '__auto_type'? AutoTypeKeyword value.
1649  unsigned Keyword : 2;
1650  };
1651 
1654 
1655  unsigned : NumTypeBits;
1656 
1657  /// The number of template arguments in \c Arguments, which is
1658  /// expected to be able to hold at least 1024 according to [implimits].
1659  /// However as this limit is somewhat easy to hit with template
1660  /// metaprogramming we'd prefer to keep it as large as possible.
1661  /// At the moment it has been left as a non-bitfield since this type
1662  /// safely fits in 64 bits as an unsigned, so there is no reason to
1663  /// introduce the performance impact of a bitfield.
1664  unsigned NumArgs;
1665  };
1666 
1669 
1670  unsigned : NumTypeBits;
1671 
1672  /// Whether this template specialization type is a substituted type alias.
1673  unsigned TypeAlias : 1;
1674 
1675  /// The number of template arguments named in this class template
1676  /// specialization, which is expected to be able to hold at least 1024
1677  /// according to [implimits]. However, as this limit is somewhat easy to
1678  /// hit with template metaprogramming we'd prefer to keep it as large
1679  /// as possible. At the moment it has been left as a non-bitfield since
1680  /// this type safely fits in 64 bits as an unsigned, so there is no reason
1681  /// to introduce the performance impact of a bitfield.
1682  unsigned NumArgs;
1683  };
1684 
1687 
1688  unsigned : NumTypeBits;
1689  unsigned : NumTypeWithKeywordBits;
1690 
1691  /// The number of template arguments named in this class template
1692  /// specialization, which is expected to be able to hold at least 1024
1693  /// according to [implimits]. However, as this limit is somewhat easy to
1694  /// hit with template metaprogramming we'd prefer to keep it as large
1695  /// as possible. At the moment it has been left as a non-bitfield since
1696  /// this type safely fits in 64 bits as an unsigned, so there is no reason
1697  /// to introduce the performance impact of a bitfield.
1698  unsigned NumArgs;
1699  };
1700 
1702  friend class PackExpansionType;
1703 
1704  unsigned : NumTypeBits;
1705 
1706  /// The number of expansions that this pack expansion will
1707  /// generate when substituted (+1), which is expected to be able to
1708  /// hold at least 1024 according to [implimits]. However, as this limit
1709  /// is somewhat easy to hit with template metaprogramming we'd prefer to
1710  /// keep it as large as possible. At the moment it has been left as a
1711  /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1712  /// there is no reason to introduce the performance impact of a bitfield.
1713  ///
1714  /// This field will only have a non-zero value when some of the parameter
1715  /// packs that occur within the pattern have been substituted but others
1716  /// have not.
1717  unsigned NumExpansions;
1718  };
1719 
1720  union {
1721  TypeBitfields TypeBits;
1737 
1738  static_assert(sizeof(TypeBitfields) <= 8,
1739  "TypeBitfields is larger than 8 bytes!");
1740  static_assert(sizeof(ArrayTypeBitfields) <= 8,
1741  "ArrayTypeBitfields is larger than 8 bytes!");
1742  static_assert(sizeof(AttributedTypeBitfields) <= 8,
1743  "AttributedTypeBitfields is larger than 8 bytes!");
1744  static_assert(sizeof(AutoTypeBitfields) <= 8,
1745  "AutoTypeBitfields is larger than 8 bytes!");
1746  static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1747  "BuiltinTypeBitfields is larger than 8 bytes!");
1748  static_assert(sizeof(FunctionTypeBitfields) <= 8,
1749  "FunctionTypeBitfields is larger than 8 bytes!");
1750  static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1751  "ObjCObjectTypeBitfields is larger than 8 bytes!");
1752  static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1753  "ReferenceTypeBitfields is larger than 8 bytes!");
1754  static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1755  "TypeWithKeywordBitfields is larger than 8 bytes!");
1756  static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1757  "ElaboratedTypeBitfields is larger than 8 bytes!");
1758  static_assert(sizeof(VectorTypeBitfields) <= 8,
1759  "VectorTypeBitfields is larger than 8 bytes!");
1760  static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1761  "SubstTemplateTypeParmPackTypeBitfields is larger"
1762  " than 8 bytes!");
1763  static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1764  "TemplateSpecializationTypeBitfields is larger"
1765  " than 8 bytes!");
1766  static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1767  "DependentTemplateSpecializationTypeBitfields is larger"
1768  " than 8 bytes!");
1769  static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1770  "PackExpansionTypeBitfields is larger than 8 bytes");
1771  };
1772 
1773 private:
1774  template <class T> friend class TypePropertyCache;
1775 
1776  /// Set whether this type comes from an AST file.
1777  void setFromAST(bool V = true) const {
1778  TypeBits.FromAST = V;
1779  }
1780 
1781 protected:
1782  friend class ASTContext;
1783 
1784  Type(TypeClass tc, QualType canon, bool Dependent,
1785  bool InstantiationDependent, bool VariablyModified,
1786  bool ContainsUnexpandedParameterPack)
1787  : ExtQualsTypeCommonBase(this,
1788  canon.isNull() ? QualType(this_(), 0) : canon) {
1789  TypeBits.TC = tc;
1790  TypeBits.Dependent = Dependent;
1791  TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1792  TypeBits.VariablyModified = VariablyModified;
1793  TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1794  TypeBits.CacheValid = false;
1795  TypeBits.CachedLocalOrUnnamed = false;
1796  TypeBits.CachedLinkage = NoLinkage;
1797  TypeBits.FromAST = false;
1798  }
1799 
1800  // silence VC++ warning C4355: 'this' : used in base member initializer list
1801  Type *this_() { return this; }
1802 
1803  void setDependent(bool D = true) {
1804  TypeBits.Dependent = D;
1805  if (D)
1806  TypeBits.InstantiationDependent = true;
1807  }
1808 
1809  void setInstantiationDependent(bool D = true) {
1810  TypeBits.InstantiationDependent = D; }
1811 
1812  void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1813 
1814  void setContainsUnexpandedParameterPack(bool PP = true) {
1815  TypeBits.ContainsUnexpandedParameterPack = PP;
1816  }
1817 
1818 public:
1819  friend class ASTReader;
1820  friend class ASTWriter;
1821 
1822  Type(const Type &) = delete;
1823  Type(Type &&) = delete;
1824  Type &operator=(const Type &) = delete;
1825  Type &operator=(Type &&) = delete;
1826 
1827  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1828 
1829  /// Whether this type comes from an AST file.
1830  bool isFromAST() const { return TypeBits.FromAST; }
1831 
1832  /// Whether this type is or contains an unexpanded parameter
1833  /// pack, used to support C++0x variadic templates.
1834  ///
1835  /// A type that contains a parameter pack shall be expanded by the
1836  /// ellipsis operator at some point. For example, the typedef in the
1837  /// following example contains an unexpanded parameter pack 'T':
1838  ///
1839  /// \code
1840  /// template<typename ...T>
1841  /// struct X {
1842  /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1843  /// };
1844  /// \endcode
1845  ///
1846  /// Note that this routine does not specify which
1848  return TypeBits.ContainsUnexpandedParameterPack;
1849  }
1850 
1851  /// Determines if this type would be canonical if it had no further
1852  /// qualification.
1853  bool isCanonicalUnqualified() const {
1854  return CanonicalType == QualType(this, 0);
1855  }
1856 
1857  /// Pull a single level of sugar off of this locally-unqualified type.
1858  /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1859  /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1860  QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1861 
1862  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1863  /// object types, function types, and incomplete types.
1864 
1865  /// Return true if this is an incomplete type.
1866  /// A type that can describe objects, but which lacks information needed to
1867  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1868  /// routine will need to determine if the size is actually required.
1869  ///
1870  /// Def If non-null, and the type refers to some kind of declaration
1871  /// that can be completed (such as a C struct, C++ class, or Objective-C
1872  /// class), will be set to the declaration.
1873  bool isIncompleteType(NamedDecl **Def = nullptr) const;
1874 
1875  /// Return true if this is an incomplete or object
1876  /// type, in other words, not a function type.
1878  return !isFunctionType();
1879  }
1880 
1881  /// Determine whether this type is an object type.
1882  bool isObjectType() const {
1883  // C++ [basic.types]p8:
1884  // An object type is a (possibly cv-qualified) type that is not a
1885  // function type, not a reference type, and not a void type.
1886  return !isReferenceType() && !isFunctionType() && !isVoidType();
1887  }
1888 
1889  /// Return true if this is a literal type
1890  /// (C++11 [basic.types]p10)
1891  bool isLiteralType(const ASTContext &Ctx) const;
1892 
1893  /// Test if this type is a standard-layout type.
1894  /// (C++0x [basic.type]p9)
1895  bool isStandardLayoutType() const;
1896 
1897  /// Helper methods to distinguish type categories. All type predicates
1898  /// operate on the canonical type, ignoring typedefs and qualifiers.
1899 
1900  /// Returns true if the type is a builtin type.
1901  bool isBuiltinType() const;
1902 
1903  /// Test for a particular builtin type.
1904  bool isSpecificBuiltinType(unsigned K) const;
1905 
1906  /// Test for a type which does not represent an actual type-system type but
1907  /// is instead used as a placeholder for various convenient purposes within
1908  /// Clang. All such types are BuiltinTypes.
1909  bool isPlaceholderType() const;
1910  const BuiltinType *getAsPlaceholderType() const;
1911 
1912  /// Test for a specific placeholder type.
1913  bool isSpecificPlaceholderType(unsigned K) const;
1914 
1915  /// Test for a placeholder type other than Overload; see
1916  /// BuiltinType::isNonOverloadPlaceholderType.
1917  bool isNonOverloadPlaceholderType() const;
1918 
1919  /// isIntegerType() does *not* include complex integers (a GCC extension).
1920  /// isComplexIntegerType() can be used to test for complex integers.
1921  bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1922  bool isEnumeralType() const;
1923 
1924  /// Determine whether this type is a scoped enumeration type.
1925  bool isScopedEnumeralType() const;
1926  bool isBooleanType() const;
1927  bool isCharType() const;
1928  bool isWideCharType() const;
1929  bool isChar8Type() const;
1930  bool isChar16Type() const;
1931  bool isChar32Type() const;
1932  bool isAnyCharacterType() const;
1933  bool isIntegralType(const ASTContext &Ctx) const;
1934 
1935  /// Determine whether this type is an integral or enumeration type.
1936  bool isIntegralOrEnumerationType() const;
1937 
1938  /// Determine whether this type is an integral or unscoped enumeration type.
1939  bool isIntegralOrUnscopedEnumerationType() const;
1940 
1941  /// Floating point categories.
1942  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1943  /// isComplexType() does *not* include complex integers (a GCC extension).
1944  /// isComplexIntegerType() can be used to test for complex integers.
1945  bool isComplexType() const; // C99 6.2.5p11 (complex)
1946  bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1947  bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1948  bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1949  bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1950  bool isFloat128Type() const;
1951  bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1952  bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1953  bool isVoidType() const; // C99 6.2.5p19
1954  bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1955  bool isAggregateType() const;
1956  bool isFundamentalType() const;
1957  bool isCompoundType() const;
1958 
1959  // Type Predicates: Check to see if this type is structurally the specified
1960  // type, ignoring typedefs and qualifiers.
1961  bool isFunctionType() const;
1962  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1963  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1964  bool isPointerType() const;
1965  bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1966  bool isBlockPointerType() const;
1967  bool isVoidPointerType() const;
1968  bool isReferenceType() const;
1969  bool isLValueReferenceType() const;
1970  bool isRValueReferenceType() const;
1971  bool isFunctionPointerType() const;
1972  bool isFunctionReferenceType() const;
1973  bool isMemberPointerType() const;
1974  bool isMemberFunctionPointerType() const;
1975  bool isMemberDataPointerType() const;
1976  bool isArrayType() const;
1977  bool isConstantArrayType() const;
1978  bool isIncompleteArrayType() const;
1979  bool isVariableArrayType() const;
1980  bool isDependentSizedArrayType() const;
1981  bool isRecordType() const;
1982  bool isClassType() const;
1983  bool isStructureType() const;
1984  bool isObjCBoxableRecordType() const;
1985  bool isInterfaceType() const;
1986  bool isStructureOrClassType() const;
1987  bool isUnionType() const;
1988  bool isComplexIntegerType() const; // GCC _Complex integer type.
1989  bool isVectorType() const; // GCC vector type.
1990  bool isExtVectorType() const; // Extended vector type.
1991  bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1992  bool isObjCObjectPointerType() const; // pointer to ObjC object
1993  bool isObjCRetainableType() const; // ObjC object or block pointer
1994  bool isObjCLifetimeType() const; // (array of)* retainable type
1995  bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1996  bool isObjCNSObjectType() const; // __attribute__((NSObject))
1997  bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1998  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1999  // for the common case.
2000  bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2001  bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2002  bool isObjCQualifiedIdType() const; // id<foo>
2003  bool isObjCQualifiedClassType() const; // Class<foo>
2004  bool isObjCObjectOrInterfaceType() const;
2005  bool isObjCIdType() const; // id
2006  bool isDecltypeType() const;
2007  /// Was this type written with the special inert-in-ARC __unsafe_unretained
2008  /// qualifier?
2009  ///
2010  /// This approximates the answer to the following question: if this
2011  /// translation unit were compiled in ARC, would this type be qualified
2012  /// with __unsafe_unretained?
2014  return hasAttr(attr::ObjCInertUnsafeUnretained);
2015  }
2016 
2017  /// Whether the type is Objective-C 'id' or a __kindof type of an
2018  /// object type, e.g., __kindof NSView * or __kindof id
2019  /// <NSCopying>.
2020  ///
2021  /// \param bound Will be set to the bound on non-id subtype types,
2022  /// which will be (possibly specialized) Objective-C class type, or
2023  /// null for 'id.
2024  bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2025  const ObjCObjectType *&bound) const;
2026 
2027  bool isObjCClassType() const; // Class
2028 
2029  /// Whether the type is Objective-C 'Class' or a __kindof type of an
2030  /// Class type, e.g., __kindof Class <NSCopying>.
2031  ///
2032  /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2033  /// here because Objective-C's type system cannot express "a class
2034  /// object for a subclass of NSFoo".
2035  bool isObjCClassOrClassKindOfType() const;
2036 
2037  bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2038  bool isObjCSelType() const; // Class
2039  bool isObjCBuiltinType() const; // 'id' or 'Class'
2040  bool isObjCARCBridgableType() const;
2041  bool isCARCBridgableType() const;
2042  bool isTemplateTypeParmType() const; // C++ template type parameter
2043  bool isNullPtrType() const; // C++11 std::nullptr_t
2044  bool isAlignValT() const; // C++17 std::align_val_t
2045  bool isStdByteType() const; // C++17 std::byte
2046  bool isAtomicType() const; // C11 _Atomic()
2047 
2048 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2049  bool is##Id##Type() const;
2050 #include "clang/Basic/OpenCLImageTypes.def"
2051 
2052  bool isImageType() const; // Any OpenCL image type
2053 
2054  bool isSamplerT() const; // OpenCL sampler_t
2055  bool isEventT() const; // OpenCL event_t
2056  bool isClkEventT() const; // OpenCL clk_event_t
2057  bool isQueueT() const; // OpenCL queue_t
2058  bool isReserveIDT() const; // OpenCL reserve_id_t
2059 
2060 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2061  bool is##Id##Type() const;
2062 #include "clang/Basic/OpenCLExtensionTypes.def"
2063  // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2064  bool isOCLIntelSubgroupAVCType() const;
2065  bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2066 
2067  bool isPipeType() const; // OpenCL pipe type
2068  bool isOpenCLSpecificType() const; // Any OpenCL specific type
2069 
2070  /// Determines if this type, which must satisfy
2071  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2072  /// than implicitly __strong.
2073  bool isObjCARCImplicitlyUnretainedType() const;
2074 
2075  /// Return the implicit lifetime for this type, which must not be dependent.
2076  Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2077 
2088  STK_FixedPoint
2089  };
2090 
2091  /// Given that this is a scalar type, classify it.
2092  ScalarTypeKind getScalarTypeKind() const;
2093 
2094  /// Whether this type is a dependent type, meaning that its definition
2095  /// somehow depends on a template parameter (C++ [temp.dep.type]).
2096  bool isDependentType() const { return TypeBits.Dependent; }
2097 
2098  /// Determine whether this type is an instantiation-dependent type,
2099  /// meaning that the type involves a template parameter (even if the
2100  /// definition does not actually depend on the type substituted for that
2101  /// template parameter).
2103  return TypeBits.InstantiationDependent;
2104  }
2105 
2106  /// Determine whether this type is an undeduced type, meaning that
2107  /// it somehow involves a C++11 'auto' type or similar which has not yet been
2108  /// deduced.
2109  bool isUndeducedType() const;
2110 
2111  /// Whether this type is a variably-modified type (C99 6.7.5).
2112  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2113 
2114  /// Whether this type involves a variable-length array type
2115  /// with a definite size.
2116  bool hasSizedVLAType() const;
2117 
2118  /// Whether this type is or contains a local or unnamed type.
2119  bool hasUnnamedOrLocalType() const;
2120 
2121  bool isOverloadableType() const;
2122 
2123  /// Determine wither this type is a C++ elaborated-type-specifier.
2124  bool isElaboratedTypeSpecifier() const;
2125 
2126  bool canDecayToPointerType() const;
2127 
2128  /// Whether this type is represented natively as a pointer. This includes
2129  /// pointers, references, block pointers, and Objective-C interface,
2130  /// qualified id, and qualified interface types, as well as nullptr_t.
2131  bool hasPointerRepresentation() const;
2132 
2133  /// Whether this type can represent an objective pointer type for the
2134  /// purpose of GC'ability
2135  bool hasObjCPointerRepresentation() const;
2136 
2137  /// Determine whether this type has an integer representation
2138  /// of some sort, e.g., it is an integer type or a vector.
2139  bool hasIntegerRepresentation() const;
2140 
2141  /// Determine whether this type has an signed integer representation
2142  /// of some sort, e.g., it is an signed integer type or a vector.
2143  bool hasSignedIntegerRepresentation() const;
2144 
2145  /// Determine whether this type has an unsigned integer representation
2146  /// of some sort, e.g., it is an unsigned integer type or a vector.
2147  bool hasUnsignedIntegerRepresentation() const;
2148 
2149  /// Determine whether this type has a floating-point representation
2150  /// of some sort, e.g., it is a floating-point type or a vector thereof.
2151  bool hasFloatingRepresentation() const;
2152 
2153  // Type Checking Functions: Check to see if this type is structurally the
2154  // specified type, ignoring typedefs and qualifiers, and return a pointer to
2155  // the best type we can.
2156  const RecordType *getAsStructureType() const;
2157  /// NOTE: getAs*ArrayType are methods on ASTContext.
2158  const RecordType *getAsUnionType() const;
2159  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2160  const ObjCObjectType *getAsObjCInterfaceType() const;
2161 
2162  // The following is a convenience method that returns an ObjCObjectPointerType
2163  // for object declared using an interface.
2164  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2165  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2166  const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2167  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2168 
2169  /// Retrieves the CXXRecordDecl that this type refers to, either
2170  /// because the type is a RecordType or because it is the injected-class-name
2171  /// type of a class template or class template partial specialization.
2172  CXXRecordDecl *getAsCXXRecordDecl() const;
2173 
2174  /// Retrieves the RecordDecl this type refers to.
2175  RecordDecl *getAsRecordDecl() const;
2176 
2177  /// Retrieves the TagDecl that this type refers to, either
2178  /// because the type is a TagType or because it is the injected-class-name
2179  /// type of a class template or class template partial specialization.
2180  TagDecl *getAsTagDecl() const;
2181 
2182  /// If this is a pointer or reference to a RecordType, return the
2183  /// CXXRecordDecl that the type refers to.
2184  ///
2185  /// If this is not a pointer or reference, or the type being pointed to does
2186  /// not refer to a CXXRecordDecl, returns NULL.
2187  const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2188 
2189  /// Get the DeducedType whose type will be deduced for a variable with
2190  /// an initializer of this type. This looks through declarators like pointer
2191  /// types, but not through decltype or typedefs.
2192  DeducedType *getContainedDeducedType() const;
2193 
2194  /// Get the AutoType whose type will be deduced for a variable with
2195  /// an initializer of this type. This looks through declarators like pointer
2196  /// types, but not through decltype or typedefs.
2198  return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2199  }
2200 
2201  /// Determine whether this type was written with a leading 'auto'
2202  /// corresponding to a trailing return type (possibly for a nested
2203  /// function type within a pointer to function type or similar).
2204  bool hasAutoForTrailingReturnType() const;
2205 
2206  /// Member-template getAs<specific type>'. Look through sugar for
2207  /// an instance of <specific type>. This scheme will eventually
2208  /// replace the specific getAsXXXX methods above.
2209  ///
2210  /// There are some specializations of this member template listed
2211  /// immediately following this class.
2212  template <typename T> const T *getAs() const;
2213 
2214  /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2215  /// of sugar (parens, attributes, etc) for an instance of <specific type>.
2216  /// This is used when you need to walk over sugar nodes that represent some
2217  /// kind of type adjustment from a type that was written as a <specific type>
2218  /// to another type that is still canonically a <specific type>.
2219  template <typename T> const T *getAsAdjusted() const;
2220 
2221  /// A variant of getAs<> for array types which silently discards
2222  /// qualifiers from the outermost type.
2223  const ArrayType *getAsArrayTypeUnsafe() const;
2224 
2225  /// Member-template castAs<specific type>. Look through sugar for
2226  /// the underlying instance of <specific type>.
2227  ///
2228  /// This method has the same relationship to getAs<T> as cast<T> has
2229  /// to dyn_cast<T>; which is to say, the underlying type *must*
2230  /// have the intended type, and this method will never return null.
2231  template <typename T> const T *castAs() const;
2232 
2233  /// A variant of castAs<> for array type which silently discards
2234  /// qualifiers from the outermost type.
2235  const ArrayType *castAsArrayTypeUnsafe() const;
2236 
2237  /// Determine whether this type had the specified attribute applied to it
2238  /// (looking through top-level type sugar).
2239  bool hasAttr(attr::Kind AK) const;
2240 
2241  /// Get the base element type of this type, potentially discarding type
2242  /// qualifiers. This should never be used when type qualifiers
2243  /// are meaningful.
2244  const Type *getBaseElementTypeUnsafe() const;
2245 
2246  /// If this is an array type, return the element type of the array,
2247  /// potentially with type qualifiers missing.
2248  /// This should never be used when type qualifiers are meaningful.
2249  const Type *getArrayElementTypeNoTypeQual() const;
2250 
2251  /// If this is a pointer type, return the pointee type.
2252  /// If this is an array type, return the array element type.
2253  /// This should never be used when type qualifiers are meaningful.
2254  const Type *getPointeeOrArrayElementType() const;
2255 
2256  /// If this is a pointer, ObjC object pointer, or block
2257  /// pointer, this returns the respective pointee.
2258  QualType getPointeeType() const;
2259 
2260  /// Return the specified type with any "sugar" removed from the type,
2261  /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2262  const Type *getUnqualifiedDesugaredType() const;
2263 
2264  /// More type predicates useful for type checking/promotion
2265  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2266 
2267  /// Return true if this is an integer type that is
2268  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2269  /// or an enum decl which has a signed representation.
2270  bool isSignedIntegerType() const;
2271 
2272  /// Return true if this is an integer type that is
2273  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2274  /// or an enum decl which has an unsigned representation.
2275  bool isUnsignedIntegerType() const;
2276 
2277  /// Determines whether this is an integer type that is signed or an
2278  /// enumeration types whose underlying type is a signed integer type.
2279  bool isSignedIntegerOrEnumerationType() const;
2280 
2281  /// Determines whether this is an integer type that is unsigned or an
2282  /// enumeration types whose underlying type is a unsigned integer type.
2283  bool isUnsignedIntegerOrEnumerationType() const;
2284 
2285  /// Return true if this is a fixed point type according to
2286  /// ISO/IEC JTC1 SC22 WG14 N1169.
2287  bool isFixedPointType() const;
2288 
2289  /// Return true if this is a fixed point or integer type.
2290  bool isFixedPointOrIntegerType() const;
2291 
2292  /// Return true if this is a saturated fixed point type according to
2293  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2294  bool isSaturatedFixedPointType() const;
2295 
2296  /// Return true if this is a saturated fixed point type according to
2297  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2298  bool isUnsaturatedFixedPointType() const;
2299 
2300  /// Return true if this is a fixed point type that is signed according
2301  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2302  bool isSignedFixedPointType() const;
2303 
2304  /// Return true if this is a fixed point type that is unsigned according
2305  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2306  bool isUnsignedFixedPointType() const;
2307 
2308  /// Return true if this is not a variable sized type,
2309  /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2310  /// incomplete types.
2311  bool isConstantSizeType() const;
2312 
2313  /// Returns true if this type can be represented by some
2314  /// set of type specifiers.
2315  bool isSpecifierType() const;
2316 
2317  /// Determine the linkage of this type.
2318  Linkage getLinkage() const;
2319 
2320  /// Determine the visibility of this type.
2322  return getLinkageAndVisibility().getVisibility();
2323  }
2324 
2325  /// Return true if the visibility was explicitly set is the code.
2326  bool isVisibilityExplicit() const {
2327  return getLinkageAndVisibility().isVisibilityExplicit();
2328  }
2329 
2330  /// Determine the linkage and visibility of this type.
2331  LinkageInfo getLinkageAndVisibility() const;
2332 
2333  /// True if the computed linkage is valid. Used for consistency
2334  /// checking. Should always return true.
2335  bool isLinkageValid() const;
2336 
2337  /// Determine the nullability of the given type.
2338  ///
2339  /// Note that nullability is only captured as sugar within the type
2340  /// system, not as part of the canonical type, so nullability will
2341  /// be lost by canonicalization and desugaring.
2342  Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2343 
2344  /// Determine whether the given type can have a nullability
2345  /// specifier applied to it, i.e., if it is any kind of pointer type.
2346  ///
2347  /// \param ResultIfUnknown The value to return if we don't yet know whether
2348  /// this type can have nullability because it is dependent.
2349  bool canHaveNullability(bool ResultIfUnknown = true) const;
2350 
2351  /// Retrieve the set of substitutions required when accessing a member
2352  /// of the Objective-C receiver type that is declared in the given context.
2353  ///
2354  /// \c *this is the type of the object we're operating on, e.g., the
2355  /// receiver for a message send or the base of a property access, and is
2356  /// expected to be of some object or object pointer type.
2357  ///
2358  /// \param dc The declaration context for which we are building up a
2359  /// substitution mapping, which should be an Objective-C class, extension,
2360  /// category, or method within.
2361  ///
2362  /// \returns an array of type arguments that can be substituted for
2363  /// the type parameters of the given declaration context in any type described
2364  /// within that context, or an empty optional to indicate that no
2365  /// substitution is required.
2367  getObjCSubstitutions(const DeclContext *dc) const;
2368 
2369  /// Determines if this is an ObjC interface type that may accept type
2370  /// parameters.
2371  bool acceptsObjCTypeParams() const;
2372 
2373  const char *getTypeClassName() const;
2374 
2376  return CanonicalType;
2377  }
2378 
2379  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2380  void dump() const;
2381  void dump(llvm::raw_ostream &OS) const;
2382 };
2383 
2384 /// This will check for a TypedefType by removing any existing sugar
2385 /// until it reaches a TypedefType or a non-sugared type.
2386 template <> const TypedefType *Type::getAs() const;
2387 
2388 /// This will check for a TemplateSpecializationType by removing any
2389 /// existing sugar until it reaches a TemplateSpecializationType or a
2390 /// non-sugared type.
2391 template <> const TemplateSpecializationType *Type::getAs() const;
2392 
2393 /// This will check for an AttributedType by removing any existing sugar
2394 /// until it reaches an AttributedType or a non-sugared type.
2395 template <> const AttributedType *Type::getAs() const;
2396 
2397 // We can do canonical leaf types faster, because we don't have to
2398 // worry about preserving child type decoration.
2399 #define TYPE(Class, Base)
2400 #define LEAF_TYPE(Class) \
2401 template <> inline const Class##Type *Type::getAs() const { \
2402  return dyn_cast<Class##Type>(CanonicalType); \
2403 } \
2404 template <> inline const Class##Type *Type::castAs() const { \
2405  return cast<Class##Type>(CanonicalType); \
2406 }
2407 #include "clang/AST/TypeNodes.def"
2408 
2409 /// This class is used for builtin types like 'int'. Builtin
2410 /// types are always canonical and have a literal name field.
2411 class BuiltinType : public Type {
2412 public:
2413  enum Kind {
2414 // OpenCL image types
2415 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2416 #include "clang/Basic/OpenCLImageTypes.def"
2417 // OpenCL extension types
2418 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2419 #include "clang/Basic/OpenCLExtensionTypes.def"
2420 // SVE Types
2421 #define SVE_TYPE(Name, Id, SingletonId) Id,
2422 #include "clang/Basic/AArch64SVEACLETypes.def"
2423 // All other builtin types
2424 #define BUILTIN_TYPE(Id, SingletonId) Id,
2425 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2426 #include "clang/AST/BuiltinTypes.def"
2427  };
2428 
2429 private:
2430  friend class ASTContext; // ASTContext creates these.
2431 
2432  BuiltinType(Kind K)
2433  : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2434  /*InstantiationDependent=*/(K == Dependent),
2435  /*VariablyModified=*/false,
2436  /*Unexpanded parameter pack=*/false) {
2437  BuiltinTypeBits.Kind = K;
2438  }
2439 
2440 public:
2441  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2442  StringRef getName(const PrintingPolicy &Policy) const;
2443 
2444  const char *getNameAsCString(const PrintingPolicy &Policy) const {
2445  // The StringRef is null-terminated.
2446  StringRef str = getName(Policy);
2447  assert(!str.empty() && str.data()[str.size()] == '\0');
2448  return str.data();
2449  }
2450 
2451  bool isSugared() const { return false; }
2452  QualType desugar() const { return QualType(this, 0); }
2453 
2454  bool isInteger() const {
2455  return getKind() >= Bool && getKind() <= Int128;
2456  }
2457 
2458  bool isSignedInteger() const {
2459  return getKind() >= Char_S && getKind() <= Int128;
2460  }
2461 
2462  bool isUnsignedInteger() const {
2463  return getKind() >= Bool && getKind() <= UInt128;
2464  }
2465 
2466  bool isFloatingPoint() const {
2467  return getKind() >= Half && getKind() <= Float128;
2468  }
2469 
2470  /// Determines whether the given kind corresponds to a placeholder type.
2471  static bool isPlaceholderTypeKind(Kind K) {
2472  return K >= Overload;
2473  }
2474 
2475  /// Determines whether this type is a placeholder type, i.e. a type
2476  /// which cannot appear in arbitrary positions in a fully-formed
2477  /// expression.
2478  bool isPlaceholderType() const {
2479  return isPlaceholderTypeKind(getKind());
2480  }
2481 
2482  /// Determines whether this type is a placeholder type other than
2483  /// Overload. Most placeholder types require only syntactic
2484  /// information about their context in order to be resolved (e.g.
2485  /// whether it is a call expression), which means they can (and
2486  /// should) be resolved in an earlier "phase" of analysis.
2487  /// Overload expressions sometimes pick up further information
2488  /// from their context, like whether the context expects a
2489  /// specific function-pointer type, and so frequently need
2490  /// special treatment.
2492  return getKind() > Overload;
2493  }
2494 
2495  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2496 };
2497 
2498 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2499 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2500 class ComplexType : public Type, public llvm::FoldingSetNode {
2501  friend class ASTContext; // ASTContext creates these.
2502 
2503  QualType ElementType;
2504 
2505  ComplexType(QualType Element, QualType CanonicalPtr)
2506  : Type(Complex, CanonicalPtr, Element->isDependentType(),
2507  Element->isInstantiationDependentType(),
2508  Element->isVariablyModifiedType(),
2509  Element->containsUnexpandedParameterPack()),
2510  ElementType(Element) {}
2511 
2512 public:
2513  QualType getElementType() const { return ElementType; }
2514 
2515  bool isSugared() const { return false; }
2516  QualType desugar() const { return QualType(this, 0); }
2517 
2518  void Profile(llvm::FoldingSetNodeID &ID) {
2519  Profile(ID, getElementType());
2520  }
2521 
2522  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2523  ID.AddPointer(Element.getAsOpaquePtr());
2524  }
2525 
2526  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2527 };
2528 
2529 /// Sugar for parentheses used when specifying types.
2530 class ParenType : public Type, public llvm::FoldingSetNode {
2531  friend class ASTContext; // ASTContext creates these.
2532 
2533  QualType Inner;
2534 
2535  ParenType(QualType InnerType, QualType CanonType)
2536  : Type(Paren, CanonType, InnerType->isDependentType(),
2537  InnerType->isInstantiationDependentType(),
2538  InnerType->isVariablyModifiedType(),
2539  InnerType->containsUnexpandedParameterPack()),
2540  Inner(InnerType) {}
2541 
2542 public:
2543  QualType getInnerType() const { return Inner; }
2544 
2545  bool isSugared() const { return true; }
2546  QualType desugar() const { return getInnerType(); }
2547 
2548  void Profile(llvm::FoldingSetNodeID &ID) {
2549  Profile(ID, getInnerType());
2550  }
2551 
2552  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2553  Inner.Profile(ID);
2554  }
2555 
2556  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2557 };
2558 
2559 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2560 class PointerType : public Type, public llvm::FoldingSetNode {
2561  friend class ASTContext; // ASTContext creates these.
2562 
2563  QualType PointeeType;
2564 
2565  PointerType(QualType Pointee, QualType CanonicalPtr)
2566  : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2567  Pointee->isInstantiationDependentType(),
2568  Pointee->isVariablyModifiedType(),
2569  Pointee->containsUnexpandedParameterPack()),
2570  PointeeType(Pointee) {}
2571 
2572 public:
2573  QualType getPointeeType() const { return PointeeType; }
2574 
2575  /// Returns true if address spaces of pointers overlap.
2576  /// OpenCL v2.0 defines conversion rules for pointers to different
2577  /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2578  /// address spaces.
2579  /// CL1.1 or CL1.2:
2580  /// address spaces overlap iff they are they same.
2581  /// CL2.0 adds:
2582  /// __generic overlaps with any address space except for __constant.
2583  bool isAddressSpaceOverlapping(const PointerType &other) const {
2584  Qualifiers thisQuals = PointeeType.getQualifiers();
2585  Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2586  // Address spaces overlap if at least one of them is a superset of another
2587  return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2588  otherQuals.isAddressSpaceSupersetOf(thisQuals);
2589  }
2590 
2591  bool isSugared() const { return false; }
2592  QualType desugar() const { return QualType(this, 0); }
2593 
2594  void Profile(llvm::FoldingSetNodeID &ID) {
2595  Profile(ID, getPointeeType());
2596  }
2597 
2598  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2599  ID.AddPointer(Pointee.getAsOpaquePtr());
2600  }
2601 
2602  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2603 };
2604 
2605 /// Represents a type which was implicitly adjusted by the semantic
2606 /// engine for arbitrary reasons. For example, array and function types can
2607 /// decay, and function types can have their calling conventions adjusted.
2608 class AdjustedType : public Type, public llvm::FoldingSetNode {
2609  QualType OriginalTy;
2610  QualType AdjustedTy;
2611 
2612 protected:
2613  friend class ASTContext; // ASTContext creates these.
2614 
2615  AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2616  QualType CanonicalPtr)
2617  : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2618  OriginalTy->isInstantiationDependentType(),
2619  OriginalTy->isVariablyModifiedType(),
2620  OriginalTy->containsUnexpandedParameterPack()),
2621  OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2622 
2623 public:
2624  QualType getOriginalType() const { return OriginalTy; }
2625  QualType getAdjustedType() const { return AdjustedTy; }
2626 
2627  bool isSugared() const { return true; }
2628  QualType desugar() const { return AdjustedTy; }
2629 
2630  void Profile(llvm::FoldingSetNodeID &ID) {
2631  Profile(ID, OriginalTy, AdjustedTy);
2632  }
2633 
2634  static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2635  ID.AddPointer(Orig.getAsOpaquePtr());
2636  ID.AddPointer(New.getAsOpaquePtr());
2637  }
2638 
2639  static bool classof(const Type *T) {
2640  return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2641  }
2642 };
2643 
2644 /// Represents a pointer type decayed from an array or function type.
2645 class DecayedType : public AdjustedType {
2646  friend class ASTContext; // ASTContext creates these.
2647 
2648  inline
2649  DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2650 
2651 public:
2652  QualType getDecayedType() const { return getAdjustedType(); }
2653 
2654  inline QualType getPointeeType() const;
2655 
2656  static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2657 };
2658 
2659 /// Pointer to a block type.
2660 /// This type is to represent types syntactically represented as
2661 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2662 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2663  friend class ASTContext; // ASTContext creates these.
2664 
2665  // Block is some kind of pointer type
2666  QualType PointeeType;
2667 
2668  BlockPointerType(QualType Pointee, QualType CanonicalCls)
2669  : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2670  Pointee->isInstantiationDependentType(),
2671  Pointee->isVariablyModifiedType(),
2672  Pointee->containsUnexpandedParameterPack()),
2673  PointeeType(Pointee) {}
2674 
2675 public:
2676  // Get the pointee type. Pointee is required to always be a function type.
2677  QualType getPointeeType() const { return PointeeType; }
2678 
2679  bool isSugared() const { return false; }
2680  QualType desugar() const { return QualType(this, 0); }
2681 
2682  void Profile(llvm::FoldingSetNodeID &ID) {
2683  Profile(ID, getPointeeType());
2684  }
2685 
2686  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2687  ID.AddPointer(Pointee.getAsOpaquePtr());
2688  }
2689 
2690  static bool classof(const Type *T) {
2691  return T->getTypeClass() == BlockPointer;
2692  }
2693 };
2694 
2695 /// Base for LValueReferenceType and RValueReferenceType
2696 class ReferenceType : public Type, public llvm::FoldingSetNode {
2697  QualType PointeeType;
2698 
2699 protected:
2700  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2701  bool SpelledAsLValue)
2702  : Type(tc, CanonicalRef, Referencee->isDependentType(),
2703  Referencee->isInstantiationDependentType(),
2704  Referencee->isVariablyModifiedType(),
2705  Referencee->containsUnexpandedParameterPack()),
2706  PointeeType(Referencee) {
2707  ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2708  ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2709  }
2710 
2711 public:
2712  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2713  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2714 
2715  QualType getPointeeTypeAsWritten() const { return PointeeType; }
2716 
2718  // FIXME: this might strip inner qualifiers; okay?
2719  const ReferenceType *T = this;
2720  while (T->isInnerRef())
2721  T = T->PointeeType->castAs<ReferenceType>();
2722  return T->PointeeType;
2723  }
2724 
2725  void Profile(llvm::FoldingSetNodeID &ID) {
2726  Profile(ID, PointeeType, isSpelledAsLValue());
2727  }
2728 
2729  static void Profile(llvm::FoldingSetNodeID &ID,
2730  QualType Referencee,
2731  bool SpelledAsLValue) {
2732  ID.AddPointer(Referencee.getAsOpaquePtr());
2733  ID.AddBoolean(SpelledAsLValue);
2734  }
2735 
2736  static bool classof(const Type *T) {
2737  return T->getTypeClass() == LValueReference ||
2738  T->getTypeClass() == RValueReference;
2739  }
2740 };
2741 
2742 /// An lvalue reference type, per C++11 [dcl.ref].
2744  friend class ASTContext; // ASTContext creates these
2745 
2746  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2747  bool SpelledAsLValue)
2748  : ReferenceType(LValueReference, Referencee, CanonicalRef,
2749  SpelledAsLValue) {}
2750 
2751 public:
2752  bool isSugared() const { return false; }
2753  QualType desugar() const { return QualType(this, 0); }
2754 
2755  static bool classof(const Type *T) {
2756  return T->getTypeClass() == LValueReference;
2757  }
2758 };
2759 
2760 /// An rvalue reference type, per C++11 [dcl.ref].
2762  friend class ASTContext; // ASTContext creates these
2763 
2764  RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2765  : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2766 
2767 public:
2768  bool isSugared() const { return false; }
2769  QualType desugar() const { return QualType(this, 0); }
2770 
2771  static bool classof(const Type *T) {
2772  return T->getTypeClass() == RValueReference;
2773  }
2774 };
2775 
2776 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2777 ///
2778 /// This includes both pointers to data members and pointer to member functions.
2779 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2780  friend class ASTContext; // ASTContext creates these.
2781 
2782  QualType PointeeType;
2783 
2784  /// The class of which the pointee is a member. Must ultimately be a
2785  /// RecordType, but could be a typedef or a template parameter too.
2786  const Type *Class;
2787 
2788  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2789  : Type(MemberPointer, CanonicalPtr,
2790  Cls->isDependentType() || Pointee->isDependentType(),
2791  (Cls->isInstantiationDependentType() ||
2792  Pointee->isInstantiationDependentType()),
2793  Pointee->isVariablyModifiedType(),
2794  (Cls->containsUnexpandedParameterPack() ||
2795  Pointee->containsUnexpandedParameterPack())),
2796  PointeeType(Pointee), Class(Cls) {}
2797 
2798 public:
2799  QualType getPointeeType() const { return PointeeType; }
2800 
2801  /// Returns true if the member type (i.e. the pointee type) is a
2802  /// function type rather than a data-member type.
2804  return PointeeType->isFunctionProtoType();
2805  }
2806 
2807  /// Returns true if the member type (i.e. the pointee type) is a
2808  /// data type rather than a function type.
2809  bool isMemberDataPointer() const {
2810  return !PointeeType->isFunctionProtoType();
2811  }
2812 
2813  const Type *getClass() const { return Class; }
2814  CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2815 
2816  bool isSugared() const { return false; }
2817  QualType desugar() const { return QualType(this, 0); }
2818 
2819  void Profile(llvm::FoldingSetNodeID &ID) {
2820  Profile(ID, getPointeeType(), getClass());
2821  }
2822 
2823  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2824  const Type *Class) {
2825  ID.AddPointer(Pointee.getAsOpaquePtr());
2826  ID.AddPointer(Class);
2827  }
2828 
2829  static bool classof(const Type *T) {
2830  return T->getTypeClass() == MemberPointer;
2831  }
2832 };
2833 
2834 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2835 class ArrayType : public Type, public llvm::FoldingSetNode {
2836 public:
2837  /// Capture whether this is a normal array (e.g. int X[4])
2838  /// an array with a static size (e.g. int X[static 4]), or an array
2839  /// with a star size (e.g. int X[*]).
2840  /// 'static' is only allowed on function parameters.
2842  Normal, Static, Star
2843  };
2844 
2845 private:
2846  /// The element type of the array.
2847  QualType ElementType;
2848 
2849 protected:
2850  friend class ASTContext; // ASTContext creates these.
2851 
2852  // C++ [temp.dep.type]p1:
2853  // A type is dependent if it is...
2854  // - an array type constructed from any dependent type or whose
2855  // size is specified by a constant expression that is
2856  // value-dependent,
2858  ArraySizeModifier sm, unsigned tq,
2859  bool ContainsUnexpandedParameterPack)
2860  : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2861  et->isInstantiationDependentType() || tc == DependentSizedArray,
2862  (tc == VariableArray || et->isVariablyModifiedType()),
2863  ContainsUnexpandedParameterPack),
2864  ElementType(et) {
2865  ArrayTypeBits.IndexTypeQuals = tq;
2866  ArrayTypeBits.SizeModifier = sm;
2867  }
2868 
2869 public:
2870  QualType getElementType() const { return ElementType; }
2871 
2873  return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2874  }
2875 
2877  return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2878  }
2879 
2880  unsigned getIndexTypeCVRQualifiers() const {
2881  return ArrayTypeBits.IndexTypeQuals;
2882  }
2883 
2884  static bool classof(const Type *T) {
2885  return T->getTypeClass() == ConstantArray ||
2886  T->getTypeClass() == VariableArray ||
2887  T->getTypeClass() == IncompleteArray ||
2888  T->getTypeClass() == DependentSizedArray;
2889  }
2890 };
2891 
2892 /// Represents the canonical version of C arrays with a specified constant size.
2893 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2894 /// ConstantArrayType where the element type is 'int' and the size is 404.
2896  llvm::APInt Size; // Allows us to unique the type.
2897 
2898  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2899  ArraySizeModifier sm, unsigned tq)
2900  : ArrayType(ConstantArray, et, can, sm, tq,
2902  Size(size) {}
2903 
2904 protected:
2905  friend class ASTContext; // ASTContext creates these.
2906 
2908  const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2909  : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2910  Size(size) {}
2911 
2912 public:
2913  const llvm::APInt &getSize() const { return Size; }
2914  bool isSugared() const { return false; }
2915  QualType desugar() const { return QualType(this, 0); }
2916 
2917  /// Determine the number of bits required to address a member of
2918  // an array with the given element type and number of elements.
2919  static unsigned getNumAddressingBits(const ASTContext &Context,
2920  QualType ElementType,
2921  const llvm::APInt &NumElements);
2922 
2923  /// Determine the maximum number of active bits that an array's size
2924  /// can require, which limits the maximum size of the array.
2925  static unsigned getMaxSizeBits(const ASTContext &Context);
2926 
2927  void Profile(llvm::FoldingSetNodeID &ID) {
2928  Profile(ID, getElementType(), getSize(),
2929  getSizeModifier(), getIndexTypeCVRQualifiers());
2930  }
2931 
2932  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2933  const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2934  unsigned TypeQuals) {
2935  ID.AddPointer(ET.getAsOpaquePtr());
2936  ID.AddInteger(ArraySize.getZExtValue());
2937  ID.AddInteger(SizeMod);
2938  ID.AddInteger(TypeQuals);
2939  }
2940 
2941  static bool classof(const Type *T) {
2942  return T->getTypeClass() == ConstantArray;
2943  }
2944 };
2945 
2946 /// Represents a C array with an unspecified size. For example 'int A[]' has
2947 /// an IncompleteArrayType where the element type is 'int' and the size is
2948 /// unspecified.
2950  friend class ASTContext; // ASTContext creates these.
2951 
2953  ArraySizeModifier sm, unsigned tq)
2954  : ArrayType(IncompleteArray, et, can, sm, tq,
2955  et->containsUnexpandedParameterPack()) {}
2956 
2957 public:
2958  friend class StmtIteratorBase;
2959 
2960  bool isSugared() const { return false; }
2961  QualType desugar() const { return QualType(this, 0); }
2962 
2963  static bool classof(const Type *T) {
2964  return T->getTypeClass() == IncompleteArray;
2965  }
2966 
2967  void Profile(llvm::FoldingSetNodeID &ID) {
2968  Profile(ID, getElementType(), getSizeModifier(),
2969  getIndexTypeCVRQualifiers());
2970  }
2971 
2972  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2973  ArraySizeModifier SizeMod, unsigned TypeQuals) {
2974  ID.AddPointer(ET.getAsOpaquePtr());
2975  ID.AddInteger(SizeMod);
2976  ID.AddInteger(TypeQuals);
2977  }
2978 };
2979 
2980 /// Represents a C array with a specified size that is not an
2981 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2982 /// Since the size expression is an arbitrary expression, we store it as such.
2983 ///
2984 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2985 /// should not be: two lexically equivalent variable array types could mean
2986 /// different things, for example, these variables do not have the same type
2987 /// dynamically:
2988 ///
2989 /// void foo(int x) {
2990 /// int Y[x];
2991 /// ++x;
2992 /// int Z[x];
2993 /// }
2995  friend class ASTContext; // ASTContext creates these.
2996 
2997  /// An assignment-expression. VLA's are only permitted within
2998  /// a function block.
2999  Stmt *SizeExpr;
3000 
3001  /// The range spanned by the left and right array brackets.
3002  SourceRange Brackets;
3003 
3005  ArraySizeModifier sm, unsigned tq,
3006  SourceRange brackets)
3007  : ArrayType(VariableArray, et, can, sm, tq,
3008  et->containsUnexpandedParameterPack()),
3009  SizeExpr((Stmt*) e), Brackets(brackets) {}
3010 
3011 public:
3012  friend class StmtIteratorBase;
3013 
3014  Expr *getSizeExpr() const {
3015  // We use C-style casts instead of cast<> here because we do not wish
3016  // to have a dependency of Type.h on Stmt.h/Expr.h.
3017  return (Expr*) SizeExpr;
3018  }
3019 
3020  SourceRange getBracketsRange() const { return Brackets; }
3021  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3022  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3023 
3024  bool isSugared() const { return false; }
3025  QualType desugar() const { return QualType(this, 0); }
3026 
3027  static bool classof(const Type *T) {
3028  return T->getTypeClass() == VariableArray;
3029  }
3030 
3031  void Profile(llvm::FoldingSetNodeID &ID) {
3032  llvm_unreachable("Cannot unique VariableArrayTypes.");
3033  }
3034 };
3035 
3036 /// Represents an array type in C++ whose size is a value-dependent expression.
3037 ///
3038 /// For example:
3039 /// \code
3040 /// template<typename T, int Size>
3041 /// class array {
3042 /// T data[Size];
3043 /// };
3044 /// \endcode
3045 ///
3046 /// For these types, we won't actually know what the array bound is
3047 /// until template instantiation occurs, at which point this will
3048 /// become either a ConstantArrayType or a VariableArrayType.
3050  friend class ASTContext; // ASTContext creates these.
3051 
3052  const ASTContext &Context;
3053 
3054  /// An assignment expression that will instantiate to the
3055  /// size of the array.
3056  ///
3057  /// The expression itself might be null, in which case the array
3058  /// type will have its size deduced from an initializer.
3059  Stmt *SizeExpr;
3060 
3061  /// The range spanned by the left and right array brackets.
3062  SourceRange Brackets;
3063 
3064  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3065  Expr *e, ArraySizeModifier sm, unsigned tq,
3066  SourceRange brackets);
3067 
3068 public:
3069  friend class StmtIteratorBase;
3070 
3071  Expr *getSizeExpr() const {
3072  // We use C-style casts instead of cast<> here because we do not wish
3073  // to have a dependency of Type.h on Stmt.h/Expr.h.
3074  return (Expr*) SizeExpr;
3075  }
3076 
3077  SourceRange getBracketsRange() const { return Brackets; }
3078  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3079  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3080 
3081  bool isSugared() const { return false; }
3082  QualType desugar() const { return QualType(this, 0); }
3083 
3084  static bool classof(const Type *T) {
3085  return T->getTypeClass() == DependentSizedArray;
3086  }
3087 
3088  void Profile(llvm::FoldingSetNodeID &ID) {
3089  Profile(ID, Context, getElementType(),
3090  getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3091  }
3092 
3093  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3094  QualType ET, ArraySizeModifier SizeMod,
3095  unsigned TypeQuals, Expr *E);
3096 };
3097 
3098 /// Represents an extended address space qualifier where the input address space
3099 /// value is dependent. Non-dependent address spaces are not represented with a
3100 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3101 ///
3102 /// For example:
3103 /// \code
3104 /// template<typename T, int AddrSpace>
3105 /// class AddressSpace {
3106 /// typedef T __attribute__((address_space(AddrSpace))) type;
3107 /// }
3108 /// \endcode
3109 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3110  friend class ASTContext;
3111 
3112  const ASTContext &Context;
3113  Expr *AddrSpaceExpr;
3114  QualType PointeeType;
3115  SourceLocation loc;
3116 
3117  DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3118  QualType can, Expr *AddrSpaceExpr,
3119  SourceLocation loc);
3120 
3121 public:
3122  Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3123  QualType getPointeeType() const { return PointeeType; }
3124  SourceLocation getAttributeLoc() const { return loc; }
3125 
3126  bool isSugared() const { return false; }
3127  QualType desugar() const { return QualType(this, 0); }
3128 
3129  static bool classof(const Type *T) {
3130  return T->getTypeClass() == DependentAddressSpace;
3131  }
3132 
3133  void Profile(llvm::FoldingSetNodeID &ID) {
3134  Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3135  }
3136 
3137  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3138  QualType PointeeType, Expr *AddrSpaceExpr);
3139 };
3140 
3141 /// Represents an extended vector type where either the type or size is
3142 /// dependent.
3143 ///
3144 /// For example:
3145 /// \code
3146 /// template<typename T, int Size>
3147 /// class vector {
3148 /// typedef T __attribute__((ext_vector_type(Size))) type;
3149 /// }
3150 /// \endcode
3151 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3152  friend class ASTContext;
3153 
3154  const ASTContext &Context;
3155  Expr *SizeExpr;
3156 
3157  /// The element type of the array.
3158  QualType ElementType;
3159 
3160  SourceLocation loc;
3161 
3162  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3163  QualType can, Expr *SizeExpr, SourceLocation loc);
3164 
3165 public:
3166  Expr *getSizeExpr() const { return SizeExpr; }
3167  QualType getElementType() const { return ElementType; }
3168  SourceLocation getAttributeLoc() const { return loc; }
3169 
3170  bool isSugared() const { return false; }
3171  QualType desugar() const { return QualType(this, 0); }
3172 
3173  static bool classof(const Type *T) {
3174  return T->getTypeClass() == DependentSizedExtVector;
3175  }
3176 
3177  void Profile(llvm::FoldingSetNodeID &ID) {
3178  Profile(ID, Context, getElementType(), getSizeExpr());
3179  }
3180 
3181  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3182  QualType ElementType, Expr *SizeExpr);
3183 };
3184 
3185 
3186 /// Represents a GCC generic vector type. This type is created using
3187 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3188 /// bytes; or from an Altivec __vector or vector declaration.
3189 /// Since the constructor takes the number of vector elements, the
3190 /// client is responsible for converting the size into the number of elements.
3191 class VectorType : public Type, public llvm::FoldingSetNode {
3192 public:
3193  enum VectorKind {
3194  /// not a target-specific vector type
3196 
3197  /// is AltiVec vector
3199 
3200  /// is AltiVec 'vector Pixel'
3202 
3203  /// is AltiVec 'vector bool ...'
3205 
3206  /// is ARM Neon vector
3208 
3209  /// is ARM Neon polynomial vector
3210  NeonPolyVector
3211  };
3212 
3213 protected:
3214  friend class ASTContext; // ASTContext creates these.
3215 
3216  /// The element type of the vector.
3218 
3219  VectorType(QualType vecType, unsigned nElements, QualType canonType,
3220  VectorKind vecKind);
3221 
3222  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3223  QualType canonType, VectorKind vecKind);
3224 
3225 public:
3226  QualType getElementType() const { return ElementType; }
3227  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3228 
3229  static bool isVectorSizeTooLarge(unsigned NumElements) {
3230  return NumElements > VectorTypeBitfields::MaxNumElements;
3231  }
3232 
3233  bool isSugared() const { return false; }
3234  QualType desugar() const { return QualType(this, 0); }
3235 
3237  return VectorKind(VectorTypeBits.VecKind);
3238  }
3239 
3240  void Profile(llvm::FoldingSetNodeID &ID) {
3241  Profile(ID, getElementType(), getNumElements(),
3242  getTypeClass(), getVectorKind());
3243  }
3244 
3245  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3246  unsigned NumElements, TypeClass TypeClass,
3247  VectorKind VecKind) {
3248  ID.AddPointer(ElementType.getAsOpaquePtr());
3249  ID.AddInteger(NumElements);
3250  ID.AddInteger(TypeClass);
3251  ID.AddInteger(VecKind);
3252  }
3253 
3254  static bool classof(const Type *T) {
3255  return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3256  }
3257 };
3258 
3259 /// Represents a vector type where either the type or size is dependent.
3260 ////
3261 /// For example:
3262 /// \code
3263 /// template<typename T, int Size>
3264 /// class vector {
3265 /// typedef T __attribute__((vector_size(Size))) type;
3266 /// }
3267 /// \endcode
3268 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3269  friend class ASTContext;
3270 
3271  const ASTContext &Context;
3272  QualType ElementType;
3273  Expr *SizeExpr;
3274  SourceLocation Loc;
3275 
3276  DependentVectorType(const ASTContext &Context, QualType ElementType,
3277  QualType CanonType, Expr *SizeExpr,
3278  SourceLocation Loc, VectorType::VectorKind vecKind);
3279 
3280 public:
3281  Expr *getSizeExpr() const { return SizeExpr; }
3282  QualType getElementType() const { return ElementType; }
3283  SourceLocation getAttributeLoc() const { return Loc; }
3285  return VectorType::VectorKind(VectorTypeBits.VecKind);
3286  }
3287 
3288  bool isSugared() const { return false; }
3289  QualType desugar() const { return QualType(this, 0); }
3290 
3291  static bool classof(const Type *T) {
3292  return T->getTypeClass() == DependentVector;
3293  }
3294 
3295  void Profile(llvm::FoldingSetNodeID &ID) {
3296  Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3297  }
3298 
3299  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3300  QualType ElementType, const Expr *SizeExpr,
3301  VectorType::VectorKind VecKind);
3302 };
3303 
3304 /// ExtVectorType - Extended vector type. This type is created using
3305 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3306 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3307 /// class enables syntactic extensions, like Vector Components for accessing
3308 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3309 /// Shading Language).
3310 class ExtVectorType : public VectorType {
3311  friend class ASTContext; // ASTContext creates these.
3312 
3313  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3314  : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3315 
3316 public:
3317  static int getPointAccessorIdx(char c) {
3318  switch (c) {
3319  default: return -1;
3320  case 'x': case 'r': return 0;
3321  case 'y': case 'g': return 1;
3322  case 'z': case 'b': return 2;
3323  case 'w': case 'a': return 3;
3324  }
3325  }
3326 
3327  static int getNumericAccessorIdx(char c) {
3328  switch (c) {
3329  default: return -1;
3330  case '0': return 0;
3331  case '1': return 1;
3332  case '2': return 2;
3333  case '3': return 3;
3334  case '4': return 4;
3335  case '5': return 5;
3336  case '6': return 6;
3337  case '7': return 7;
3338  case '8': return 8;
3339  case '9': return 9;
3340  case 'A':
3341  case 'a': return 10;
3342  case 'B':
3343  case 'b': return 11;
3344  case 'C':
3345  case 'c': return 12;
3346  case 'D':
3347  case 'd': return 13;
3348  case 'E':
3349  case 'e': return 14;
3350  case 'F':
3351  case 'f': return 15;
3352  }
3353  }
3354 
3355  static int getAccessorIdx(char c, bool isNumericAccessor) {
3356  if (isNumericAccessor)
3357  return getNumericAccessorIdx(c);
3358  else
3359  return getPointAccessorIdx(c);
3360  }
3361 
3362  bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3363  if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3364  return unsigned(idx-1) < getNumElements();
3365  return false;
3366  }
3367 
3368  bool isSugared() const { return false; }
3369  QualType desugar() const { return QualType(this, 0); }
3370 
3371  static bool classof(const Type *T) {
3372  return T->getTypeClass() == ExtVector;
3373  }
3374 };
3375 
3376 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3377 /// class of FunctionNoProtoType and FunctionProtoType.
3378 class FunctionType : public Type {
3379  // The type returned by the function.
3380  QualType ResultType;
3381 
3382 public:
3383  /// Interesting information about a specific parameter that can't simply
3384  /// be reflected in parameter's type. This is only used by FunctionProtoType
3385  /// but is in FunctionType to make this class available during the
3386  /// specification of the bases of FunctionProtoType.
3387  ///
3388  /// It makes sense to model language features this way when there's some
3389  /// sort of parameter-specific override (such as an attribute) that
3390  /// affects how the function is called. For example, the ARC ns_consumed
3391  /// attribute changes whether a parameter is passed at +0 (the default)
3392  /// or +1 (ns_consumed). This must be reflected in the function type,
3393  /// but isn't really a change to the parameter type.
3394  ///
3395  /// One serious disadvantage of modelling language features this way is
3396  /// that they generally do not work with language features that attempt
3397  /// to destructure types. For example, template argument deduction will
3398  /// not be able to match a parameter declared as
3399  /// T (*)(U)
3400  /// against an argument of type
3401  /// void (*)(__attribute__((ns_consumed)) id)
3402  /// because the substitution of T=void, U=id into the former will
3403  /// not produce the latter.
3405  enum {
3406  ABIMask = 0x0F,
3407  IsConsumed = 0x10,
3408  HasPassObjSize = 0x20,
3409  IsNoEscape = 0x40,
3410  };
3411  unsigned char Data = 0;
3412 
3413  public:
3414  ExtParameterInfo() = default;
3415 
3416  /// Return the ABI treatment of this parameter.
3417  ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3419  ExtParameterInfo copy = *this;
3420  copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3421  return copy;
3422  }
3423 
3424  /// Is this parameter considered "consumed" by Objective-C ARC?
3425  /// Consumed parameters must have retainable object type.
3426  bool isConsumed() const { return (Data & IsConsumed); }
3427  ExtParameterInfo withIsConsumed(bool consumed) const {
3428  ExtParameterInfo copy = *this;
3429  if (consumed)
3430  copy.Data |= IsConsumed;
3431  else
3432  copy.Data &= ~IsConsumed;
3433  return copy;
3434  }
3435 
3436  bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3438  ExtParameterInfo Copy = *this;
3439  Copy.Data |= HasPassObjSize;
3440  return Copy;
3441  }
3442 
3443  bool isNoEscape() const { return Data & IsNoEscape; }
3444  ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3445  ExtParameterInfo Copy = *this;
3446  if (NoEscape)
3447  Copy.Data |= IsNoEscape;
3448  else
3449  Copy.Data &= ~IsNoEscape;
3450  return Copy;
3451  }
3452 
3453  unsigned char getOpaqueValue() const { return Data; }
3454  static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3455  ExtParameterInfo result;
3456  result.Data = data;
3457  return result;
3458  }
3459 
3461  return lhs.Data == rhs.Data;
3462  }
3463 
3465  return lhs.Data != rhs.Data;
3466  }
3467  };
3468 
3469  /// A class which abstracts out some details necessary for
3470  /// making a call.
3471  ///
3472  /// It is not actually used directly for storing this information in
3473  /// a FunctionType, although FunctionType does currently use the
3474  /// same bit-pattern.
3475  ///
3476  // If you add a field (say Foo), other than the obvious places (both,
3477  // constructors, compile failures), what you need to update is
3478  // * Operator==
3479  // * getFoo
3480  // * withFoo
3481  // * functionType. Add Foo, getFoo.
3482  // * ASTContext::getFooType
3483  // * ASTContext::mergeFunctionTypes
3484  // * FunctionNoProtoType::Profile
3485  // * FunctionProtoType::Profile
3486  // * TypePrinter::PrintFunctionProto
3487  // * AST read and write
3488  // * Codegen
3489  class ExtInfo {
3490  friend class FunctionType;
3491 
3492  // Feel free to rearrange or add bits, but if you go over 12,
3493  // you'll need to adjust both the Bits field below and
3494  // Type::FunctionTypeBitfields.
3495 
3496  // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3497  // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3498  //
3499  // regparm is either 0 (no regparm attribute) or the regparm value+1.
3500  enum { CallConvMask = 0x1F };
3501  enum { NoReturnMask = 0x20 };
3502  enum { ProducesResultMask = 0x40 };
3503  enum { NoCallerSavedRegsMask = 0x80 };
3504  enum { NoCfCheckMask = 0x800 };
3505  enum {
3506  RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3507  NoCallerSavedRegsMask | NoCfCheckMask),
3508  RegParmOffset = 8
3509  }; // Assumed to be the last field
3510  uint16_t Bits = CC_C;
3511 
3512  ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3513 
3514  public:
3515  // Constructor with no defaults. Use this when you know that you
3516  // have all the elements (when reading an AST file for example).
3517  ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3518  bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3519  assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3520  Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3521  (producesResult ? ProducesResultMask : 0) |
3522  (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3523  (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3524  (NoCfCheck ? NoCfCheckMask : 0);
3525  }
3526 
3527  // Constructor with all defaults. Use when for example creating a
3528  // function known to use defaults.
3529  ExtInfo() = default;
3530 
3531  // Constructor with just the calling convention, which is an important part
3532  // of the canonical type.
3533  ExtInfo(CallingConv CC) : Bits(CC) {}
3534 
3535  bool getNoReturn() const { return Bits & NoReturnMask; }
3536  bool getProducesResult() const { return Bits & ProducesResultMask; }
3537  bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3538  bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3539  bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3540 
3541  unsigned getRegParm() const {
3542  unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3543  if (RegParm > 0)
3544  --RegParm;
3545  return RegParm;
3546  }
3547 
3548  CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3549 
3550  bool operator==(ExtInfo Other) const {
3551  return Bits == Other.Bits;
3552  }
3553  bool operator!=(ExtInfo Other) const {
3554  return Bits != Other.Bits;
3555  }
3556 
3557  // Note that we don't have setters. That is by design, use
3558  // the following with methods instead of mutating these objects.
3559 
3560  ExtInfo withNoReturn(bool noReturn) const {
3561  if (noReturn)
3562  return ExtInfo(Bits | NoReturnMask);
3563  else
3564  return ExtInfo(Bits & ~NoReturnMask);
3565  }
3566 
3567  ExtInfo withProducesResult(bool producesResult) const {
3568  if (producesResult)
3569  return ExtInfo(Bits | ProducesResultMask);
3570  else
3571  return ExtInfo(Bits & ~ProducesResultMask);
3572  }
3573 
3574  ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3575  if (noCallerSavedRegs)
3576  return ExtInfo(Bits | NoCallerSavedRegsMask);
3577  else
3578  return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3579  }
3580 
3581  ExtInfo withNoCfCheck(bool noCfCheck) const {
3582  if (noCfCheck)
3583  return ExtInfo(Bits | NoCfCheckMask);
3584  else
3585  return ExtInfo(Bits & ~NoCfCheckMask);
3586  }
3587 
3588  ExtInfo withRegParm(unsigned RegParm) const {
3589  assert(RegParm < 7 && "Invalid regparm value");
3590  return ExtInfo((Bits & ~RegParmMask) |
3591  ((RegParm + 1) << RegParmOffset));
3592  }
3593 
3595  return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3596  }
3597 
3598  void Profile(llvm::FoldingSetNodeID &ID) const {
3599  ID.AddInteger(Bits);
3600  }
3601  };
3602 
3603  /// A simple holder for a QualType representing a type in an
3604  /// exception specification. Unfortunately needed by FunctionProtoType
3605  /// because TrailingObjects cannot handle repeated types.
3607 
3608  /// A simple holder for various uncommon bits which do not fit in
3609  /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3610  /// alignment of subsequent objects in TrailingObjects. You must update
3611  /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3612  struct alignas(void *) FunctionTypeExtraBitfields {
3613  /// The number of types in the exception specification.
3614  /// A whole unsigned is not needed here and according to
3615  /// [implimits] 8 bits would be enough here.
3617  };
3618 
3619 protected:
3621  QualType Canonical, bool Dependent,
3622  bool InstantiationDependent,
3623  bool VariablyModified, bool ContainsUnexpandedParameterPack,
3624  ExtInfo Info)
3625  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3626  ContainsUnexpandedParameterPack),
3627  ResultType(res) {
3628  FunctionTypeBits.ExtInfo = Info.Bits;
3629  }
3630 
3632  return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3633  }
3634 
3635 public:
3636  QualType getReturnType() const { return ResultType; }
3637 
3638  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3639  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3640 
3641  /// Determine whether this function type includes the GNU noreturn
3642  /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3643  /// type.
3644  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3645 
3646  CallingConv getCallConv() const { return getExtInfo().getCC(); }
3647  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3648 
3649  static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3650  "Const, volatile and restrict are assumed to be a subset of "
3651  "the fast qualifiers.");
3652 
3653  bool isConst() const { return getFastTypeQuals().hasConst(); }
3654  bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3655  bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3656 
3657  /// Determine the type of an expression that calls a function of
3658  /// this type.
3659  QualType getCallResultType(const ASTContext &Context) const {
3660  return getReturnType().getNonLValueExprType(Context);
3661  }
3662 
3663  static StringRef getNameForCallConv(CallingConv CC);
3664 
3665  static bool classof(const Type *T) {
3666  return T->getTypeClass() == FunctionNoProto ||
3667  T->getTypeClass() == FunctionProto;
3668  }
3669 };
3670 
3671 /// Represents a K&R-style 'int foo()' function, which has
3672 /// no information available about its arguments.
3673 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3674  friend class ASTContext; // ASTContext creates these.
3675 
3677  : FunctionType(FunctionNoProto, Result, Canonical,
3678  /*Dependent=*/false, /*InstantiationDependent=*/false,
3679  Result->isVariablyModifiedType(),
3680  /*ContainsUnexpandedParameterPack=*/false, Info) {}
3681 
3682 public:
3683  // No additional state past what FunctionType provides.
3684 
3685  bool isSugared() const { return false; }
3686  QualType desugar() const { return QualType(this, 0); }
3687 
3688  void Profile(llvm::FoldingSetNodeID &ID) {
3689  Profile(ID, getReturnType(), getExtInfo());
3690  }
3691 
3692  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3693  ExtInfo Info) {
3694  Info.Profile(ID);
3695  ID.AddPointer(ResultType.getAsOpaquePtr());
3696  }
3697 
3698  static bool classof(const Type *T) {
3699  return T->getTypeClass() == FunctionNoProto;
3700  }
3701 };
3702 
3703 /// Represents a prototype with parameter type info, e.g.
3704 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3705 /// parameters, not as having a single void parameter. Such a type can have
3706 /// an exception specification, but this specification is not part of the
3707 /// canonical type. FunctionProtoType has several trailing objects, some of
3708 /// which optional. For more information about the trailing objects see
3709 /// the first comment inside FunctionProtoType.
3711  : public FunctionType,
3712  public llvm::FoldingSetNode,
3713  private llvm::TrailingObjects<
3714  FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3715  FunctionType::ExceptionType, Expr *, FunctionDecl *,
3716  FunctionType::ExtParameterInfo, Qualifiers> {
3717  friend class ASTContext; // ASTContext creates these.
3718  friend TrailingObjects;
3719 
3720  // FunctionProtoType is followed by several trailing objects, some of
3721  // which optional. They are in order:
3722  //
3723  // * An array of getNumParams() QualType holding the parameter types.
3724  // Always present. Note that for the vast majority of FunctionProtoType,
3725  // these will be the only trailing objects.
3726  //
3727  // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3728  // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3729  // a single FunctionTypeExtraBitfields. Present if and only if
3730  // hasExtraBitfields() is true.
3731  //
3732  // * Optionally exactly one of:
3733  // * an array of getNumExceptions() ExceptionType,
3734  // * a single Expr *,
3735  // * a pair of FunctionDecl *,
3736  // * a single FunctionDecl *
3737  // used to store information about the various types of exception
3738  // specification. See getExceptionSpecSize for the details.
3739  //
3740  // * Optionally an array of getNumParams() ExtParameterInfo holding
3741  // an ExtParameterInfo for each of the parameters. Present if and
3742  // only if hasExtParameterInfos() is true.
3743  //
3744  // * Optionally a Qualifiers object to represent extra qualifiers that can't
3745  // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3746  // if hasExtQualifiers() is true.
3747  //
3748  // The optional FunctionTypeExtraBitfields has to be before the data
3749  // related to the exception specification since it contains the number
3750  // of exception types.
3751  //
3752  // We put the ExtParameterInfos last. If all were equal, it would make
3753  // more sense to put these before the exception specification, because
3754  // it's much easier to skip past them compared to the elaborate switch
3755  // required to skip the exception specification. However, all is not
3756  // equal; ExtParameterInfos are used to model very uncommon features,
3757  // and it's better not to burden the more common paths.
3758 
3759 public:
3760  /// Holds information about the various types of exception specification.
3761  /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3762  /// used to group together the various bits of information about the
3763  /// exception specification.
3765  /// The kind of exception specification this is.
3767 
3768  /// Explicitly-specified list of exception types.
3770 
3771  /// Noexcept expression, if this is a computed noexcept specification.
3772  Expr *NoexceptExpr = nullptr;
3773 
3774  /// The function whose exception specification this is, for
3775  /// EST_Unevaluated and EST_Uninstantiated.
3776  FunctionDecl *SourceDecl = nullptr;
3777 
3778  /// The function template whose exception specification this is instantiated
3779  /// from, for EST_Uninstantiated.
3780  FunctionDecl *SourceTemplate = nullptr;
3781 
3782  ExceptionSpecInfo() = default;
3783 
3785  };
3786 
3787  /// Extra information about a function prototype. ExtProtoInfo is not
3788  /// stored as such in FunctionProtoType but is used to group together
3789  /// the various bits of extra information about a function prototype.
3790  struct ExtProtoInfo {
3792  bool Variadic : 1;
3795  RefQualifierKind RefQualifier = RQ_None;
3797  const ExtParameterInfo *ExtParameterInfos = nullptr;
3798 
3799  ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3800 
3802  : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3803 
3805  ExtProtoInfo Result(*this);
3806  Result.ExceptionSpec = ESI;
3807  return Result;
3808  }
3809  };
3810 
3811 private:
3812  unsigned numTrailingObjects(OverloadToken<QualType>) const {
3813  return getNumParams();
3814  }
3815 
3816  unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3817  return hasExtraBitfields();
3818  }
3819 
3820  unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3821  return getExceptionSpecSize().NumExceptionType;
3822  }
3823 
3824  unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3825  return getExceptionSpecSize().NumExprPtr;
3826  }
3827 
3828  unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3829  return getExceptionSpecSize().NumFunctionDeclPtr;
3830  }
3831 
3832  unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3833  return hasExtParameterInfos() ? getNumParams() : 0;
3834  }
3835 
3836  /// Determine whether there are any argument types that
3837  /// contain an unexpanded parameter pack.
3838  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3839  unsigned numArgs) {
3840  for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3841  if (ArgArray[Idx]->containsUnexpandedParameterPack())
3842  return true;
3843 
3844  return false;
3845  }
3846 
3848  QualType canonical, const ExtProtoInfo &epi);
3849 
3850  /// This struct is returned by getExceptionSpecSize and is used to
3851  /// translate an ExceptionSpecificationType to the number and kind
3852  /// of trailing objects related to the exception specification.
3853  struct ExceptionSpecSizeHolder {
3854  unsigned NumExceptionType;
3855  unsigned NumExprPtr;
3856  unsigned NumFunctionDeclPtr;
3857  };
3858 
3859  /// Return the number and kind of trailing objects
3860  /// related to the exception specification.
3861  static ExceptionSpecSizeHolder
3862  getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3863  switch (EST) {
3864  case EST_None:
3865  case EST_DynamicNone:
3866  case EST_MSAny:
3867  case EST_BasicNoexcept:
3868  case EST_Unparsed:
3869  case EST_NoThrow:
3870  return {0, 0, 0};
3871 
3872  case EST_Dynamic:
3873  return {NumExceptions, 0, 0};
3874 
3875  case EST_DependentNoexcept:
3876  case EST_NoexceptFalse:
3877  case EST_NoexceptTrue:
3878  return {0, 1, 0};
3879 
3880  case EST_Uninstantiated:
3881  return {0, 0, 2};
3882 
3883  case EST_Unevaluated:
3884  return {0, 0, 1};
3885  }
3886  llvm_unreachable("bad exception specification kind");
3887  }
3888 
3889  /// Return the number and kind of trailing objects
3890  /// related to the exception specification.
3891  ExceptionSpecSizeHolder getExceptionSpecSize() const {
3892  return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3893  }
3894 
3895  /// Whether the trailing FunctionTypeExtraBitfields is present.
3896  static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3897  // If the exception spec type is EST_Dynamic then we have > 0 exception
3898  // types and the exact number is stored in FunctionTypeExtraBitfields.
3899  return EST == EST_Dynamic;
3900  }
3901 
3902  /// Whether the trailing FunctionTypeExtraBitfields is present.
3903  bool hasExtraBitfields() const {
3904  return hasExtraBitfields(getExceptionSpecType());
3905  }
3906 
3907  bool hasExtQualifiers() const {
3908  return FunctionTypeBits.HasExtQuals;
3909  }
3910 
3911 public:
3912  unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3913 
3914  QualType getParamType(unsigned i) const {
3915  assert(i < getNumParams() && "invalid parameter index");
3916  return param_type_begin()[i];
3917  }
3918 
3920  return llvm::makeArrayRef(param_type_begin(), param_type_end());
3921  }
3922 
3924  ExtProtoInfo EPI;
3925  EPI.ExtInfo = getExtInfo();
3926  EPI.Variadic = isVariadic();
3927  EPI.HasTrailingReturn = hasTrailingReturn();
3928  EPI.ExceptionSpec.Type = getExceptionSpecType();
3929  EPI.TypeQuals = getMethodQuals();
3930  EPI.RefQualifier = getRefQualifier();
3931  if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3932  EPI.ExceptionSpec.Exceptions = exceptions();
3933  } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3934  EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3935  } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3936  EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3937  EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3938  } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3939  EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3940  }
3941  EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3942  return EPI;
3943  }
3944 
3945  /// Get the kind of exception specification on this function.
3947  return static_cast<ExceptionSpecificationType>(
3948  FunctionTypeBits.ExceptionSpecType);
3949  }
3950 
3951  /// Return whether this function has any kind of exception spec.
3952  bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3953 
3954  /// Return whether this function has a dynamic (throw) exception spec.
3956  return isDynamicExceptionSpec(getExceptionSpecType());
3957  }
3958 
3959  /// Return whether this function has a noexcept exception spec.
3961  return isNoexceptExceptionSpec(getExceptionSpecType());
3962  }
3963 
3964  /// Return whether this function has a dependent exception spec.
3965  bool hasDependentExceptionSpec() const;
3966 
3967  /// Return whether this function has an instantiation-dependent exception
3968  /// spec.
3969  bool hasInstantiationDependentExceptionSpec() const;
3970 
3971  /// Return the number of types in the exception specification.
3972  unsigned getNumExceptions() const {
3973  return getExceptionSpecType() == EST_Dynamic
3974  ? getTrailingObjects<FunctionTypeExtraBitfields>()
3975  ->NumExceptionType
3976  : 0;
3977  }
3978 
3979  /// Return the ith exception type, where 0 <= i < getNumExceptions().
3980  QualType getExceptionType(unsigned i) const {
3981  assert(i < getNumExceptions() && "Invalid exception number!");
3982  return exception_begin()[i];
3983  }
3984 
3985  /// Return the expression inside noexcept(expression), or a null pointer
3986  /// if there is none (because the exception spec is not of this form).
3988  if (!isComputedNoexcept(getExceptionSpecType()))
3989  return nullptr;
3990  return *getTrailingObjects<Expr *>();
3991  }
3992 
3993  /// If this function type has an exception specification which hasn't
3994  /// been determined yet (either because it has not been evaluated or because
3995  /// it has not been instantiated), this is the function whose exception
3996  /// specification is represented by this type.
3998  if (getExceptionSpecType() != EST_Uninstantiated &&
3999  getExceptionSpecType() != EST_Unevaluated)
4000  return nullptr;
4001  return getTrailingObjects<FunctionDecl *>()[0];
4002  }
4003 
4004  /// If this function type has an uninstantiated exception
4005  /// specification, this is the function whose exception specification
4006  /// should be instantiated to find the exception specification for
4007  /// this type.
4009  if (getExceptionSpecType() != EST_Uninstantiated)
4010  return nullptr;
4011  return getTrailingObjects<FunctionDecl *>()[1];
4012  }
4013 
4014  /// Determine whether this function type has a non-throwing exception
4015  /// specification.
4016  CanThrowResult canThrow() const;
4017 
4018  /// Determine whether this function type has a non-throwing exception
4019  /// specification. If this depends on template arguments, returns
4020  /// \c ResultIfDependent.
4021  bool isNothrow(bool ResultIfDependent = false) const {
4022  return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4023  }
4024 
4025  /// Whether this function prototype is variadic.
4026  bool isVariadic() const { return FunctionTypeBits.Variadic; }
4027 
4028  /// Determines whether this function prototype contains a
4029  /// parameter pack at the end.
4030  ///
4031  /// A function template whose last parameter is a parameter pack can be
4032  /// called with an arbitrary number of arguments, much like a variadic
4033  /// function.
4034  bool isTemplateVariadic() const;
4035 
4036  /// Whether this function prototype has a trailing return type.
4037  bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4038 
4040  if (hasExtQualifiers())
4041  return *getTrailingObjects<Qualifiers>();
4042  else
4043  return getFastTypeQuals();
4044  }
4045 
4046  /// Retrieve the ref-qualifier associated with this function type.
4048  return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4049  }
4050 
4052  using param_type_range = llvm::iterator_range<param_type_iterator>;
4053 
4055  return param_type_range(param_type_begin(), param_type_end());
4056  }
4057 
4059  return getTrailingObjects<QualType>();
4060  }
4061 
4063  return param_type_begin() + getNumParams();
4064  }
4065 
4066  using exception_iterator = const QualType *;
4067 
4069  return llvm::makeArrayRef(exception_begin(), exception_end());
4070  }
4071 
4073  return reinterpret_cast<exception_iterator>(
4074  getTrailingObjects<ExceptionType>());
4075  }
4076 
4078  return exception_begin() + getNumExceptions();
4079  }
4080 
4081  /// Is there any interesting extra information for any of the parameters
4082  /// of this function type?
4083  bool hasExtParameterInfos() const {
4084  return FunctionTypeBits.HasExtParameterInfos;
4085  }
4086 
4088  assert(hasExtParameterInfos());
4089  return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4090  getNumParams());
4091  }
4092 
4093  /// Return a pointer to the beginning of the array of extra parameter
4094  /// information, if present, or else null if none of the parameters
4095  /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4097  if (!hasExtParameterInfos())
4098  return nullptr;
4099  return getTrailingObjects<ExtParameterInfo>();
4100  }
4101 
4103  assert(I < getNumParams() && "parameter index out of range");
4104  if (hasExtParameterInfos())
4105  return getTrailingObjects<ExtParameterInfo>()[I];
4106  return ExtParameterInfo();
4107  }
4108 
4109  ParameterABI getParameterABI(unsigned I) const {
4110  assert(I < getNumParams() && "parameter index out of range");
4111  if (hasExtParameterInfos())
4112  return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4113  return ParameterABI::Ordinary;
4114  }
4115 
4116  bool isParamConsumed(unsigned I) const {
4117  assert(I < getNumParams() && "parameter index out of range");
4118  if (hasExtParameterInfos())
4119  return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4120  return false;
4121  }
4122 
4123  bool isSugared() const { return false; }
4124  QualType desugar() const { return QualType(this, 0); }
4125 
4126  void printExceptionSpecification(raw_ostream &OS,
4127  const PrintingPolicy &Policy) const;
4128 
4129  static bool classof(const Type *T) {
4130  return T->getTypeClass() == FunctionProto;
4131  }
4132 
4133  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4134  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4135  param_type_iterator ArgTys, unsigned NumArgs,
4136  const ExtProtoInfo &EPI, const ASTContext &Context,
4137  bool Canonical);
4138 };
4139 
4140 /// Represents the dependent type named by a dependently-scoped
4141 /// typename using declaration, e.g.
4142 /// using typename Base<T>::foo;
4143 ///
4144 /// Template instantiation turns these into the underlying type.
4145 class UnresolvedUsingType : public Type {
4146  friend class ASTContext; // ASTContext creates these.
4147 
4149 
4151  : Type(UnresolvedUsing, QualType(), true, true, false,
4152  /*ContainsUnexpandedParameterPack=*/false),
4153  Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4154 
4155 public:
4156  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4157 
4158  bool isSugared() const { return false; }
4159  QualType desugar() const { return QualType(this, 0); }
4160 
4161  static bool classof(const Type *T) {
4162  return T->getTypeClass() == UnresolvedUsing;
4163  }
4164 
4165  void Profile(llvm::FoldingSetNodeID &ID) {
4166  return Profile(ID, Decl);
4167  }
4168 
4169  static void Profile(llvm::FoldingSetNodeID &ID,
4171  ID.AddPointer(D);
4172  }
4173 };
4174 
4175 class TypedefType : public Type {
4177 
4178 protected:
4179  friend class ASTContext; // ASTContext creates these.
4180 
4182  : Type(tc, can, can->isDependentType(),
4183  can->isInstantiationDependentType(),
4184  can->isVariablyModifiedType(),
4185  /*ContainsUnexpandedParameterPack=*/false),
4186  Decl(const_cast<TypedefNameDecl*>(D)) {
4187  assert(!isa<TypedefType>(can) && "Invalid canonical type");
4188  }
4189 
4190 public:
4191  TypedefNameDecl *getDecl() const { return Decl; }
4192 
4193  bool isSugared() const { return true; }
4194  QualType desugar() const;
4195 
4196  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4197 };
4198 
4199 /// Sugar type that represents a type that was qualified by a qualifier written
4200 /// as a macro invocation.
4201 class MacroQualifiedType : public Type {
4202  friend class ASTContext; // ASTContext creates these.
4203 
4204  QualType UnderlyingTy;
4205  const IdentifierInfo *MacroII;
4206 
4207  MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4208  const IdentifierInfo *MacroII)
4209  : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4210  UnderlyingTy->isInstantiationDependentType(),
4211  UnderlyingTy->isVariablyModifiedType(),
4212  UnderlyingTy->containsUnexpandedParameterPack()),
4213  UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4214  assert(isa<AttributedType>(UnderlyingTy) &&
4215  "Expected a macro qualified type to only wrap attributed types.");
4216  }
4217 
4218 public:
4219  const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4220  QualType getUnderlyingType() const { return UnderlyingTy; }
4221 
4222  /// Return this attributed type's modified type with no qualifiers attached to
4223  /// it.
4224  QualType getModifiedType() const;
4225 
4226  bool isSugared() const { return true; }
4227  QualType desugar() const;
4228 
4229  static bool classof(const Type *T) {
4230  return T->getTypeClass() == MacroQualified;
4231  }
4232 };
4233 
4234 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4235 class TypeOfExprType : public Type {
4236  Expr *TOExpr;
4237 
4238 protected:
4239  friend class ASTContext; // ASTContext creates these.
4240 
4241  TypeOfExprType(Expr *E, QualType can = QualType());
4242 
4243 public:
4244  Expr *getUnderlyingExpr() const { return TOExpr; }
4245 
4246  /// Remove a single level of sugar.
4247  QualType desugar() const;
4248 
4249  /// Returns whether this type directly provides sugar.
4250  bool isSugared() const;
4251 
4252  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4253 };
4254 
4255 /// Internal representation of canonical, dependent
4256 /// `typeof(expr)` types.
4257 ///
4258 /// This class is used internally by the ASTContext to manage
4259 /// canonical, dependent types, only. Clients will only see instances
4260 /// of this class via TypeOfExprType nodes.
4262  : public TypeOfExprType, public llvm::FoldingSetNode {
4263  const ASTContext &Context;
4264 
4265 public:
4267  : TypeOfExprType(E), Context(Context) {}
4268 
4269  void Profile(llvm::FoldingSetNodeID &ID) {
4270  Profile(ID, Context, getUnderlyingExpr());
4271  }
4272 
4273  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4274  Expr *E);
4275 };
4276 
4277 /// Represents `typeof(type)`, a GCC extension.
4278 class TypeOfType : public Type {
4279  friend class ASTContext; // ASTContext creates these.
4280 
4281  QualType TOType;
4282 
4283  TypeOfType(QualType T, QualType can)
4284  : Type(TypeOf, can, T->isDependentType(),
4285  T->isInstantiationDependentType(),
4286  T->isVariablyModifiedType(),
4287  T->containsUnexpandedParameterPack()),
4288  TOType(T) {
4289  assert(!isa<TypedefType>(can) && "Invalid canonical type");
4290  }
4291 
4292 public:
4293  QualType getUnderlyingType() const { return TOType; }
4294 
4295  /// Remove a single level of sugar.
4296  QualType desugar() const { return getUnderlyingType(); }
4297 
4298  /// Returns whether this type directly provides sugar.
4299  bool isSugared() const { return true; }
4300 
4301  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4302 };
4303 
4304 /// Represents the type `decltype(expr)` (C++11).
4305 class DecltypeType : public Type {
4306  Expr *E;
4307  QualType UnderlyingType;
4308 
4309 protected:
4310  friend class ASTContext; // ASTContext creates these.
4311 
4312  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4313 
4314 public:
4315  Expr *getUnderlyingExpr() const { return E; }
4316  QualType getUnderlyingType() const { return UnderlyingType; }
4317 
4318  /// Remove a single level of sugar.
4319  QualType desugar() const;
4320 
4321  /// Returns whether this type directly provides sugar.
4322  bool isSugared() const;
4323 
4324  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4325 };
4326 
4327 /// Internal representation of canonical, dependent
4328 /// decltype(expr) types.
4329 ///
4330 /// This class is used internally by the ASTContext to manage
4331 /// canonical, dependent types, only. Clients will only see instances
4332 /// of this class via DecltypeType nodes.
4333 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4334  const ASTContext &Context;
4335 
4336 public:
4337  DependentDecltypeType(const ASTContext &Context, Expr *E);
4338 
4339  void Profile(llvm::FoldingSetNodeID &ID) {
4340  Profile(ID, Context, getUnderlyingExpr());
4341  }
4342 
4343  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4344  Expr *E);
4345 };
4346 
4347 /// A unary type transform, which is a type constructed from another.
4348 class UnaryTransformType : public Type {
4349 public:
4350  enum UTTKind {
4351  EnumUnderlyingType
4352  };
4353 
4354 private:
4355  /// The untransformed type.
4356  QualType BaseType;
4357 
4358  /// The transformed type if not dependent, otherwise the same as BaseType.
4359  QualType UnderlyingType;
4360 
4361  UTTKind UKind;
4362 
4363 protected:
4364  friend class ASTContext;
4365 
4366  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4367  QualType CanonicalTy);
4368 
4369 public:
4370  bool isSugared() const { return !isDependentType(); }
4371  QualType desugar() const { return UnderlyingType; }
4372 
4373  QualType getUnderlyingType() const { return UnderlyingType; }
4374  QualType getBaseType() const { return BaseType; }
4375 
4376  UTTKind getUTTKind() const { return UKind; }
4377 
4378  static bool classof(const Type *T) {
4379  return T->getTypeClass() == UnaryTransform;
4380  }
4381 };
4382 
4383 /// Internal representation of canonical, dependent
4384 /// __underlying_type(type) types.
4385 ///
4386 /// This class is used internally by the ASTContext to manage
4387 /// canonical, dependent types, only. Clients will only see instances
4388 /// of this class via UnaryTransformType nodes.
4390  public llvm::FoldingSetNode {
4391 public:
4393  UTTKind UKind);
4394 
4395  void Profile(llvm::FoldingSetNodeID &ID) {
4396  Profile(ID, getBaseType(), getUTTKind());
4397  }
4398 
4399  static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4400  UTTKind UKind) {
4401  ID.AddPointer(BaseType.getAsOpaquePtr());
4402  ID.AddInteger((unsigned)UKind);
4403  }
4404 };
4405 
4406 class TagType : public Type {
4407  friend class ASTReader;
4408 
4409  /// Stores the TagDecl associated with this type. The decl may point to any
4410  /// TagDecl that declares the entity.
4411  TagDecl *decl;
4412 
4413 protected:
4414  TagType(TypeClass TC, const TagDecl *D, QualType can);
4415 
4416 public:
4417  TagDecl *getDecl() const;
4418 
4419  /// Determines whether this type is in the process of being defined.
4420  bool isBeingDefined() const;
4421 
4422  static bool classof(const Type *T) {
4423  return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4424  }
4425 };
4426 
4427 /// A helper class that allows the use of isa/cast/dyncast
4428 /// to detect TagType objects of structs/unions/classes.
4429 class RecordType : public TagType {
4430 protected:
4431  friend class ASTContext; // ASTContext creates these.
4432 
4433  explicit RecordType(const RecordDecl *D)
4434  : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4436  : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4437 
4438 public:
4439  RecordDecl *getDecl() const {
4440  return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4441  }
4442 
4443  /// Recursively check all fields in the record for const-ness. If any field
4444  /// is declared const, return true. Otherwise, return false.
4445  bool hasConstFields() const;
4446 
4447  bool isSugared() const { return false; }
4448  QualType desugar() const { return QualType(this, 0); }
4449 
4450  static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4451 };
4452 
4453 /// A helper class that allows the use of isa/cast/dyncast
4454 /// to detect TagType objects of enums.
4455 class EnumType : public TagType {
4456  friend class ASTContext; // ASTContext creates these.
4457 
4458  explicit EnumType(const EnumDecl *D)
4459  : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4460 
4461 public:
4462  EnumDecl *getDecl() const {
4463  return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4464  }
4465 
4466  bool isSugared() const { return false; }
4467  QualType desugar() const { return QualType(this, 0); }
4468 
4469  static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4470 };
4471 
4472 /// An attributed type is a type to which a type attribute has been applied.
4473 ///
4474 /// The "modified type" is the fully-sugared type to which the attributed
4475 /// type was applied; generally it is not canonically equivalent to the
4476 /// attributed type. The "equivalent type" is the minimally-desugared type
4477 /// which the type is canonically equivalent to.
4478 ///
4479 /// For example, in the following attributed type:
4480 /// int32_t __attribute__((vector_size(16)))
4481 /// - the modified type is the TypedefType for int32_t
4482 /// - the equivalent type is VectorType(16, int32_t)
4483 /// - the canonical type is VectorType(16, int)
4484 class AttributedType : public Type, public llvm::FoldingSetNode {
4485 public:
4486  using Kind = attr::Kind;
4487 
4488 private:
4489  friend class ASTContext; // ASTContext creates these
4490 
4491  QualType ModifiedType;
4492  QualType EquivalentType;
4493 
4494  AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4495  QualType equivalent)
4496  : Type(Attributed, canon, equivalent->isDependentType(),
4497  equivalent->isInstantiationDependentType(),
4498  equivalent->isVariablyModifiedType(),
4499  equivalent->containsUnexpandedParameterPack()),
4500  ModifiedType(modified), EquivalentType(equivalent) {
4501  AttributedTypeBits.AttrKind = attrKind;
4502  }
4503 
4504 public:
4505  Kind getAttrKind() const {
4506  return static_cast<Kind>(AttributedTypeBits.AttrKind);
4507  }
4508 
4509  QualType getModifiedType() const { return ModifiedType; }
4510  QualType getEquivalentType() const { return EquivalentType; }
4511 
4512  bool isSugared() const { return true; }
4513  QualType desugar() const { return getEquivalentType(); }
4514 
4515  /// Does this attribute behave like a type qualifier?
4516  ///
4517  /// A type qualifier adjusts a type to provide specialized rules for
4518  /// a specific object, like the standard const and volatile qualifiers.
4519  /// This includes attributes controlling things like nullability,
4520  /// address spaces, and ARC ownership. The value of the object is still
4521  /// largely described by the modified type.
4522  ///
4523  /// In contrast, many type attributes "rewrite" their modified type to
4524  /// produce a fundamentally different type, not necessarily related in any
4525  /// formalizable way to the original type. For example, calling convention
4526  /// and vector attributes are not simple type qualifiers.
4527  ///
4528  /// Type qualifiers are often, but not always, reflected in the canonical
4529  /// type.
4530  bool isQualifier() const;
4531 
4532  bool isMSTypeSpec() const;
4533 
4534  bool isCallingConv() const;
4535 
4536  llvm::Optional<NullabilityKind> getImmediateNullability() const;
4537 
4538  /// Retrieve the attribute kind corresponding to the given
4539  /// nullability kind.
4541  switch (kind) {
4543  return attr::TypeNonNull;
4544 
4546  return attr::TypeNullable;
4547 
4549  return attr::TypeNullUnspecified;
4550  }
4551  llvm_unreachable("Unknown nullability kind.");
4552  }
4553 
4554  /// Strip off the top-level nullability annotation on the given
4555  /// type, if it's there.
4556  ///
4557  /// \param T The type to strip. If the type is exactly an
4558  /// AttributedType specifying nullability (without looking through
4559  /// type sugar), the nullability is returned and this type changed
4560  /// to the underlying modified type.
4561  ///
4562  /// \returns the top-level nullability, if present.
4563  static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4564 
4565  void Profile(llvm::FoldingSetNodeID &ID) {
4566  Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4567  }
4568 
4569  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4570  QualType modified, QualType equivalent) {
4571  ID.AddInteger(attrKind);
4572  ID.AddPointer(modified.getAsOpaquePtr());
4573  ID.AddPointer(equivalent.getAsOpaquePtr());
4574  }
4575 
4576  static bool classof(const Type *T) {
4577  return T->getTypeClass() == Attributed;
4578  }
4579 };
4580 
4581 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4582  friend class ASTContext; // ASTContext creates these
4583 
4584  // Helper data collector for canonical types.
4585  struct CanonicalTTPTInfo {
4586  unsigned Depth : 15;
4587  unsigned ParameterPack : 1;
4588  unsigned Index : 16;
4589  };
4590 
4591  union {
4592  // Info for the canonical type.
4593  CanonicalTTPTInfo CanTTPTInfo;
4594 
4595  // Info for the non-canonical type.
4597  };
4598 
4599  /// Build a non-canonical type.
4601  : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4602  /*InstantiationDependent=*/true,
4603  /*VariablyModified=*/false,
4604  Canon->containsUnexpandedParameterPack()),
4605  TTPDecl(TTPDecl) {}
4606 
4607  /// Build the canonical type.
4608  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4609  : Type(TemplateTypeParm, QualType(this, 0),
4610  /*Dependent=*/true,
4611  /*InstantiationDependent=*/true,
4612  /*VariablyModified=*/false, PP) {
4613  CanTTPTInfo.Depth = D;
4614  CanTTPTInfo.Index = I;
4615  CanTTPTInfo.ParameterPack = PP;
4616  }
4617 
4618  const CanonicalTTPTInfo& getCanTTPTInfo() const {
4619  QualType Can = getCanonicalTypeInternal();
4620  return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4621  }
4622 
4623 public:
4624  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4625  unsigned getIndex() const { return getCanTTPTInfo().Index; }
4626  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4627 
4629  return isCanonicalUnqualified() ? nullptr : TTPDecl;
4630  }
4631 
4632  IdentifierInfo *getIdentifier() const;
4633 
4634  bool isSugared() const { return false; }
4635  QualType desugar() const { return QualType(this, 0); }
4636 
4637  void Profile(llvm::FoldingSetNodeID &ID) {
4638  Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4639  }
4640 
4641  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4642  unsigned Index, bool ParameterPack,
4643  TemplateTypeParmDecl *TTPDecl) {
4644  ID.AddInteger(Depth);
4645  ID.AddInteger(Index);
4646  ID.AddBoolean(ParameterPack);
4647  ID.AddPointer(TTPDecl);
4648  }
4649 
4650  static bool classof(const Type *T) {
4651  return T->getTypeClass() == TemplateTypeParm;
4652  }
4653 };
4654 
4655 /// Represents the result of substituting a type for a template
4656 /// type parameter.
4657 ///
4658 /// Within an instantiated template, all template type parameters have
4659 /// been replaced with these. They are used solely to record that a
4660 /// type was originally written as a template type parameter;
4661 /// therefore they are never canonical.
4662 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4663  friend class ASTContext;
4664 
4665  // The original type parameter.
4666  const TemplateTypeParmType *Replaced;
4667 
4669  : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4670  Canon->isInstantiationDependentType(),
4671  Canon->isVariablyModifiedType(),
4672  Canon->containsUnexpandedParameterPack()),
4673  Replaced(Param) {}
4674 
4675 public:
4676  /// Gets the template parameter that was substituted for.
4678  return Replaced;
4679  }
4680 
4681  /// Gets the type that was substituted for the template
4682  /// parameter.
4684  return getCanonicalTypeInternal();
4685  }
4686 
4687  bool isSugared() const { return true; }
4688  QualType desugar() const { return getReplacementType(); }
4689 
4690  void Profile(llvm::FoldingSetNodeID &ID) {
4691  Profile(ID, getReplacedParameter(), getReplacementType());
4692  }
4693 
4694  static void Profile(llvm::FoldingSetNodeID &ID,
4695  const TemplateTypeParmType *Replaced,
4696  QualType Replacement) {
4697  ID.AddPointer(Replaced);
4698  ID.AddPointer(Replacement.getAsOpaquePtr());
4699  }
4700 
4701  static bool classof(const Type *T) {
4702  return T->getTypeClass() == SubstTemplateTypeParm;
4703  }
4704 };
4705 
4706 /// Represents the result of substituting a set of types for a template
4707 /// type parameter pack.
4708 ///
4709 /// When a pack expansion in the source code contains multiple parameter packs
4710 /// and those parameter packs correspond to different levels of template
4711 /// parameter lists, this type node is used to represent a template type
4712 /// parameter pack from an outer level, which has already had its argument pack
4713 /// substituted but that still lives within a pack expansion that itself
4714 /// could not be instantiated. When actually performing a substitution into
4715 /// that pack expansion (e.g., when all template parameters have corresponding
4716 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4717 /// at the current pack substitution index.
4718 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4719  friend class ASTContext;
4720 
4721  /// The original type parameter.
4722  const TemplateTypeParmType *Replaced;
4723 
4724  /// A pointer to the set of template arguments that this
4725  /// parameter pack is instantiated with.
4726  const TemplateArgument *Arguments;
4727 
4729  QualType Canon,
4730  const TemplateArgument &ArgPack);
4731 
4732 public:
4733  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4734 
4735  /// Gets the template parameter that was substituted for.
4737  return Replaced;
4738  }
4739 
4740  unsigned getNumArgs() const {
4741  return SubstTemplateTypeParmPackTypeBits.NumArgs;
4742  }
4743 
4744  bool isSugared() const { return false; }
4745  QualType desugar() const { return QualType(this, 0); }
4746 
4747  TemplateArgument getArgumentPack() const;
4748 
4749  void Profile(llvm::FoldingSetNodeID &ID);
4750  static void Profile(llvm::FoldingSetNodeID &ID,
4751  const TemplateTypeParmType *Replaced,
4752  const TemplateArgument &ArgPack);
4753 
4754  static bool classof(const Type *T) {
4755  return T->getTypeClass() == SubstTemplateTypeParmPack;
4756  }
4757 };
4758 
4759 /// Common base class for placeholders for types that get replaced by
4760 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4761 /// class template types, and (eventually) constrained type names from the C++
4762 /// Concepts TS.
4763 ///
4764 /// These types are usually a placeholder for a deduced type. However, before
4765 /// the initializer is attached, or (usually) if the initializer is
4766 /// type-dependent, there is no deduced type and the type is canonical. In
4767 /// the latter case, it is also a dependent type.
4768 class DeducedType : public Type {
4769 protected:
4770  DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4771  bool IsInstantiationDependent, bool ContainsParameterPack)
4772  : Type(TC,
4773  // FIXME: Retain the sugared deduced type?
4774  DeducedAsType.isNull() ? QualType(this, 0)
4775  : DeducedAsType.getCanonicalType(),
4776  IsDependent, IsInstantiationDependent,
4777  /*VariablyModified=*/false, ContainsParameterPack) {
4778  if (!DeducedAsType.isNull()) {
4779  if (DeducedAsType->isDependentType())
4780  setDependent();
4781  if (DeducedAsType->isInstantiationDependentType())
4782  setInstantiationDependent();
4783  if (DeducedAsType->containsUnexpandedParameterPack())
4784  setContainsUnexpandedParameterPack();
4785  }
4786  }
4787 
4788 public:
4789  bool isSugared() const { return !isCanonicalUnqualified(); }
4790  QualType desugar() const { return getCanonicalTypeInternal(); }
4791 
4792  /// Get the type deduced for this placeholder type, or null if it's
4793  /// either not been deduced or was deduced to a dependent type.
4795  return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4796  }
4797  bool isDeduced() const {
4798  return !isCanonicalUnqualified() || isDependentType();
4799  }
4800 
4801  static bool classof(const Type *T) {
4802  return T->getTypeClass() == Auto ||
4803  T->getTypeClass() == DeducedTemplateSpecialization;
4804  }
4805 };
4806 
4807 /// Represents a C++11 auto or C++14 decltype(auto) type.
4808 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4809  friend class ASTContext; // ASTContext creates these
4810 
4811  AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4812  bool IsDeducedAsDependent, bool IsDeducedAsPack)
4813  : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4814  IsDeducedAsDependent, IsDeducedAsPack) {
4815  AutoTypeBits.Keyword = (unsigned)Keyword;
4816  }
4817 
4818 public:
4819  bool isDecltypeAuto() const {
4820  return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4821  }
4822 
4824  return (AutoTypeKeyword)AutoTypeBits.Keyword;
4825  }
4826 
4827  void Profile(llvm::FoldingSetNodeID &ID) {
4828  Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4829  containsUnexpandedParameterPack());
4830  }
4831 
4832  static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4833  AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4834  ID.AddPointer(Deduced.getAsOpaquePtr());
4835  ID.AddInteger((unsigned)Keyword);
4836  ID.AddBoolean(IsDependent);
4837  ID.AddBoolean(IsPack);
4838  }
4839 
4840  static bool classof(const Type *T) {
4841  return T->getTypeClass() == Auto;
4842  }
4843 };
4844 
4845 /// Represents a C++17 deduced template specialization type.
4847  public llvm::FoldingSetNode {
4848  friend class ASTContext; // ASTContext creates these
4849 
4850  /// The name of the template whose arguments will be deduced.
4851  TemplateName Template;
4852 
4854  QualType DeducedAsType,
4855  bool IsDeducedAsDependent)
4856  : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4857  IsDeducedAsDependent || Template.isDependent(),
4858  IsDeducedAsDependent || Template.isInstantiationDependent(),
4859  Template.containsUnexpandedParameterPack()),
4860  Template(Template) {}
4861 
4862 public:
4863  /// Retrieve the name of the template that we are deducing.
4864  TemplateName getTemplateName() const { return Template;}
4865 
4866  void Profile(llvm::FoldingSetNodeID &ID) {
4867  Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4868  }
4869 
4870  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4871  QualType Deduced, bool IsDependent) {
4872  Template.Profile(ID);
4873  ID.AddPointer(Deduced.getAsOpaquePtr());
4874  ID.AddBoolean(IsDependent);
4875  }
4876 
4877  static bool classof(const Type *T) {
4878  return T->getTypeClass() == DeducedTemplateSpecialization;
4879  }
4880 };
4881 
4882 /// Represents a type template specialization; the template
4883 /// must be a class template, a type alias template, or a template
4884 /// template parameter. A template which cannot be resolved to one of
4885 /// these, e.g. because it is written with a dependent scope
4886 /// specifier, is instead represented as a
4887 /// @c DependentTemplateSpecializationType.
4888 ///
4889 /// A non-dependent template specialization type is always "sugar",
4890 /// typically for a \c RecordType. For example, a class template
4891 /// specialization type of \c vector<int> will refer to a tag type for
4892 /// the instantiation \c std::vector<int, std::allocator<int>>
4893 ///
4894 /// Template specializations are dependent if either the template or
4895 /// any of the template arguments are dependent, in which case the
4896 /// type may also be canonical.
4897 ///
4898 /// Instances of this type are allocated with a trailing array of
4899 /// TemplateArguments, followed by a QualType representing the
4900 /// non-canonical aliased type when the template is a type alias
4901 /// template.
4903  : public Type,
4904  public llvm::FoldingSetNode {
4905  friend class ASTContext; // ASTContext creates these
4906 
4907  /// The name of the template being specialized. This is
4908  /// either a TemplateName::Template (in which case it is a
4909  /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4910  /// TypeAliasTemplateDecl*), a
4911  /// TemplateName::SubstTemplateTemplateParmPack, or a
4912  /// TemplateName::SubstTemplateTemplateParm (in which case the
4913  /// replacement must, recursively, be one of these).
4914  TemplateName Template;
4915 
4918  QualType Canon,
4919  QualType Aliased);
4920 
4921 public:
4922  /// Determine whether any of the given template arguments are dependent.
4923  static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4924  bool &InstantiationDependent);
4925 
4926  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4927  bool &InstantiationDependent);
4928 
4929  /// True if this template specialization type matches a current
4930  /// instantiation in the context in which it is found.
4931  bool isCurrentInstantiation() const {
4932  return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4933  }
4934 
4935  /// Determine if this template specialization type is for a type alias
4936  /// template that has been substituted.
4937  ///
4938  /// Nearly every template specialization type whose template is an alias
4939  /// template will be substituted. However, this is not the case when
4940  /// the specialization contains a pack expansion but the template alias
4941  /// does not have a corresponding parameter pack, e.g.,
4942  ///
4943  /// \code
4944  /// template<typename T, typename U, typename V> struct S;
4945  /// template<typename T, typename U> using A = S<T, int, U>;
4946  /// template<typename... Ts> struct X {
4947  /// typedef A<Ts...> type; // not a type alias
4948  /// };
4949  /// \endcode
4950  bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4951 
4952  /// Get the aliased type, if this is a specialization of a type alias
4953  /// template.
4955  assert(isTypeAlias() && "not a type alias template specialization");
4956  return *reinterpret_cast<const QualType*>(end());
4957  }
4958 
4959  using iterator = const TemplateArgument *;
4960 
4961  iterator begin() const { return getArgs(); }
4962  iterator end() const; // defined inline in TemplateBase.h
4963 
4964  /// Retrieve the name of the template that we are specializing.
4965  TemplateName getTemplateName() const { return Template; }
4966 
4967  /// Retrieve the template arguments.
4968  const TemplateArgument *getArgs() const {
4969  return reinterpret_cast<const TemplateArgument *>(this + 1);
4970  }
4971 
4972  /// Retrieve the number of template arguments.
4973  unsigned getNumArgs() const {
4974  return TemplateSpecializationTypeBits.NumArgs;
4975  }
4976 
4977  /// Retrieve a specific template argument as a type.
4978  /// \pre \c isArgType(Arg)
4979  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4980 
4982  return {getArgs(), getNumArgs()};
4983  }
4984 
4985  bool isSugared() const {
4986  return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4987  }
4988 
4989  QualType desugar() const {
4990  return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
4991  }
4992 
4993  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4994  Profile(ID, Template, template_arguments(), Ctx);
4995  if (isTypeAlias())
4996  getAliasedType().Profile(ID);
4997  }
4998 
4999  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5001  const ASTContext &Context);
5002 
5003  static bool classof(const Type *T) {
5004  return T->getTypeClass() == TemplateSpecialization;
5005  }
5006 };
5007 
5008 /// Print a template argument list, including the '<' and '>'
5009 /// enclosing the template arguments.
5010 void printTemplateArgumentList(raw_ostream &OS,
5012  const PrintingPolicy &Policy);
5013 
5014 void printTemplateArgumentList(raw_ostream &OS,
5016  const PrintingPolicy &Policy);
5017 
5018 void printTemplateArgumentList(raw_ostream &OS,
5019  const TemplateArgumentListInfo &Args,
5020  const PrintingPolicy &Policy);
5021 
5022 /// The injected class name of a C++ class template or class
5023 /// template partial specialization. Used to record that a type was
5024 /// spelled with a bare identifier rather than as a template-id; the
5025 /// equivalent for non-templated classes is just RecordType.
5026 ///
5027 /// Injected class name types are always dependent. Template
5028 /// instantiation turns these into RecordTypes.
5029 ///
5030 /// Injected class name types are always canonical. This works
5031 /// because it is impossible to compare an injected class name type
5032 /// with the corresponding non-injected template type, for the same
5033 /// reason that it is impossible to directly compare template
5034 /// parameters from different dependent contexts: injected class name
5035 /// types can only occur within the scope of a particular templated
5036 /// declaration, and within that scope every template specialization
5037 /// will canonicalize to the injected class name (when appropriate
5038 /// according to the rules of the language).
5039 class InjectedClassNameType : public Type {
5040  friend class ASTContext; // ASTContext creates these.
5041  friend class ASTNodeImporter;
5042  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5043  // currently suitable for AST reading, too much
5044  // interdependencies.
5045 
5047 
5048  /// The template specialization which this type represents.
5049  /// For example, in
5050  /// template <class T> class A { ... };
5051  /// this is A<T>, whereas in
5052  /// template <class X, class Y> class A<B<X,Y> > { ... };
5053  /// this is A<B<X,Y> >.
5054  ///
5055  /// It is always unqualified, always a template specialization type,
5056  /// and always dependent.
5057  QualType InjectedType;
5058 
5060  : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5061  /*InstantiationDependent=*/true,
5062  /*VariablyModified=*/false,
5063  /*ContainsUnexpandedParameterPack=*/false),
5064  Decl(D), InjectedType(TST) {
5065  assert(isa<TemplateSpecializationType>(TST));
5066  assert(!TST.hasQualifiers());
5067  assert(TST->isDependentType());
5068  }
5069 
5070 public:
5071  QualType getInjectedSpecializationType() const { return InjectedType; }
5072 
5074  return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5075  }
5076 
5078  return getInjectedTST()->getTemplateName();
5079  }
5080 
5081  CXXRecordDecl *getDecl() const;
5082 
5083  bool isSugared() const { return false; }
5084  QualType desugar() const { return QualType(this, 0); }
5085 
5086  static bool classof(const Type *T) {
5087  return T->getTypeClass() == InjectedClassName;
5088  }
5089 };
5090 
5091 /// The kind of a tag type.
5093  /// The "struct" keyword.
5095 
5096  /// The "__interface" keyword.
5098 
5099  /// The "union" keyword.
5101 
5102  /// The "class" keyword.
5104 
5105  /// The "enum" keyword.
5107 };
5108 
5109 /// The elaboration keyword that precedes a qualified type name or
5110 /// introduces an elaborated-type-specifier.
5112  /// The "struct" keyword introduces the elaborated-type-specifier.
5114 
5115  /// The "__interface" keyword introduces the elaborated-type-specifier.
5117 
5118  /// The "union" keyword introduces the elaborated-type-specifier.
5120 
5121  /// The "class" keyword introduces the elaborated-type-specifier.
5123 
5124  /// The "enum" keyword introduces the elaborated-type-specifier.
5126 
5127  /// The "typename" keyword precedes the qualified type name, e.g.,
5128  /// \c typename T::type.
5130 
5131  /// No keyword precedes the qualified type name.
5133 };
5134 
5135 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
5136 /// The keyword in stored in the free bits of the base class.
5137 /// Also provides a few static helpers for converting and printing
5138 /// elaborated type keyword and tag type kind enumerations.
5139 class TypeWithKeyword : public Type {
5140 protected:
5142  QualType Canonical, bool Dependent,
5143  bool InstantiationDependent, bool VariablyModified,
5144  bool ContainsUnexpandedParameterPack)
5145  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5146  ContainsUnexpandedParameterPack) {
5147  TypeWithKeywordBits.Keyword = Keyword;
5148  }
5149 
5150 public:
5152  return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5153  }
5154 
5155  /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5156  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5157 
5158  /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5159  /// It is an error to provide a type specifier which *isn't* a tag kind here.
5160  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5161 
5162  /// Converts a TagTypeKind into an elaborated type keyword.
5163  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5164 
5165  /// Converts an elaborated type keyword into a TagTypeKind.
5166  /// It is an error to provide an elaborated type keyword
5167  /// which *isn't* a tag kind here.
5168  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5169 
5170  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5171 
5172  static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5173 
5175  return getKeywordName(getKeywordForTagTypeKind(Kind));
5176  }
5177 
5179  static CannotCastToThisType classof(const Type *);
5180 };
5181 
5182 /// Represents a type that was referred to using an elaborated type
5183 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5184 /// or both.
5185 ///
5186 /// This type is used to keep track of a type name as written in the
5187 /// source code, including tag keywords and any nested-name-specifiers.
5188 /// The type itself is always "sugar", used to express what was written
5189 /// in the source code but containing no additional semantic information.
5190 class ElaboratedType final
5191  : public TypeWithKeyword,
5192  public llvm::FoldingSetNode,
5193  private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5194  friend class ASTContext; // ASTContext creates these
5195  friend TrailingObjects;
5196 
5197  /// The nested name specifier containing the qualifier.
5198  NestedNameSpecifier *NNS;
5199 
5200  /// The type that this qualified name refers to.
5201  QualType NamedType;
5202 
5203  /// The (re)declaration of this tag type owned by this occurrence is stored
5204  /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5205  /// it, or obtain a null pointer if there is none.
5206 
5208  QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5209  : TypeWithKeyword(Keyword, Elaborated, CanonType,
5210  NamedType->isDependentType(),
5211  NamedType->isInstantiationDependentType(),
5212  NamedType->isVariablyModifiedType(),
5213  NamedType->containsUnexpandedParameterPack()),
5214  NNS(NNS), NamedType(NamedType) {
5215  ElaboratedTypeBits.HasOwnedTagDecl = false;
5216  if (OwnedTagDecl) {
5217  ElaboratedTypeBits.HasOwnedTagDecl = true;
5218  *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5219  }
5220  assert(!(Keyword == ETK_None && NNS == nullptr) &&
5221  "ElaboratedType cannot have elaborated type keyword "
5222  "and name qualifier both null.");
5223  }
5224 
5225 public:
5226  /// Retrieve the qualification on this type.
5227  NestedNameSpecifier *getQualifier() const { return NNS; }
5228 
5229  /// Retrieve the type named by the qualified-id.
5230  QualType getNamedType() const { return NamedType; }
5231 
5232  /// Remove a single level of sugar.
5233  QualType desugar() const { return getNamedType(); }
5234 
5235  /// Returns whether this type directly provides sugar.
5236  bool isSugared() const { return true; }
5237 
5238  /// Return the (re)declaration of this type owned by this occurrence of this
5239  /// type, or nullptr if there is none.
5241  return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5242  : nullptr;
5243  }
5244 
5245  void