Type.h revision afcfd753e6c5d50edb13dd0b7f46fc40f6aa8fa0
1//===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Type interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_TYPE_H
15#define LLVM_CLANG_AST_TYPE_H
16
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/AST/NestedNameSpecifier.h"
20#include "clang/AST/TemplateName.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/type_traits.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/PointerUnion.h"
27
28using llvm::isa;
29using llvm::cast;
30using llvm::cast_or_null;
31using llvm::dyn_cast;
32using llvm::dyn_cast_or_null;
33namespace clang {
34  enum {
35    TypeAlignmentInBits = 3,
36    TypeAlignment = 1 << TypeAlignmentInBits
37  };
38  class Type; class ExtQuals;
39}
40
41namespace llvm {
42  template <typename T>
43  class PointerLikeTypeTraits;
44  template<>
45  class PointerLikeTypeTraits< ::clang::Type*> {
46  public:
47    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
48    static inline ::clang::Type *getFromVoidPointer(void *P) {
49      return static_cast< ::clang::Type*>(P);
50    }
51    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
52  };
53  template<>
54  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
55  public:
56    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
57    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
58      return static_cast< ::clang::ExtQuals*>(P);
59    }
60    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
61  };
62}
63
64namespace clang {
65  class ASTContext;
66  class TypedefDecl;
67  class TemplateDecl;
68  class TemplateTypeParmDecl;
69  class NonTypeTemplateParmDecl;
70  class TemplateTemplateParmDecl;
71  class TagDecl;
72  class RecordDecl;
73  class CXXRecordDecl;
74  class EnumDecl;
75  class FieldDecl;
76  class ObjCInterfaceDecl;
77  class ObjCProtocolDecl;
78  class ObjCMethodDecl;
79  class Expr;
80  class Stmt;
81  class SourceLocation;
82  class StmtIteratorBase;
83  class TemplateArgument;
84  class TemplateArgumentLoc;
85  class QualifiedNameType;
86  struct PrintingPolicy;
87
88  // Provide forward declarations for all of the *Type classes
89#define TYPE(Class, Base) class Class##Type;
90#include "clang/AST/TypeNodes.def"
91
92/// Qualifiers - The collection of all-type qualifiers we support.
93/// Clang supports five independent qualifiers:
94/// * C99: const, volatile, and restrict
95/// * Embedded C (TR18037): address spaces
96/// * Objective C: the GC attributes (none, weak, or strong)
97class Qualifiers {
98public:
99  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
100    Const    = 0x1,
101    Restrict = 0x2,
102    Volatile = 0x4,
103    CVRMask = Const | Volatile | Restrict
104  };
105
106  enum GC {
107    GCNone = 0,
108    Weak,
109    Strong
110  };
111
112  enum {
113    /// The maximum supported address space number.
114    /// 24 bits should be enough for anyone.
115    MaxAddressSpace = 0xffffffu,
116
117    /// The width of the "fast" qualifier mask.
118    FastWidth = 2,
119
120    /// The fast qualifier mask.
121    FastMask = (1 << FastWidth) - 1
122  };
123
124  Qualifiers() : Mask(0) {}
125
126  static Qualifiers fromFastMask(unsigned Mask) {
127    Qualifiers Qs;
128    Qs.addFastQualifiers(Mask);
129    return Qs;
130  }
131
132  static Qualifiers fromCVRMask(unsigned CVR) {
133    Qualifiers Qs;
134    Qs.addCVRQualifiers(CVR);
135    return Qs;
136  }
137
138  // Deserialize qualifiers from an opaque representation.
139  static Qualifiers fromOpaqueValue(unsigned opaque) {
140    Qualifiers Qs;
141    Qs.Mask = opaque;
142    return Qs;
143  }
144
145  // Serialize these qualifiers into an opaque representation.
146  unsigned getAsOpaqueValue() const {
147    return Mask;
148  }
149
150  bool hasConst() const { return Mask & Const; }
151  void setConst(bool flag) {
152    Mask = (Mask & ~Const) | (flag ? Const : 0);
153  }
154  void removeConst() { Mask &= ~Const; }
155  void addConst() { Mask |= Const; }
156
157  bool hasVolatile() const { return Mask & Volatile; }
158  void setVolatile(bool flag) {
159    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
160  }
161  void removeVolatile() { Mask &= ~Volatile; }
162  void addVolatile() { Mask |= Volatile; }
163
164  bool hasRestrict() const { return Mask & Restrict; }
165  void setRestrict(bool flag) {
166    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
167  }
168  void removeRestrict() { Mask &= ~Restrict; }
169  void addRestrict() { Mask |= Restrict; }
170
171  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
172  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
173  void setCVRQualifiers(unsigned mask) {
174    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
175    Mask = (Mask & ~CVRMask) | mask;
176  }
177  void removeCVRQualifiers(unsigned mask) {
178    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
179    Mask &= ~mask;
180  }
181  void removeCVRQualifiers() {
182    removeCVRQualifiers(CVRMask);
183  }
184  void addCVRQualifiers(unsigned mask) {
185    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
186    Mask |= mask;
187  }
188
189  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
190  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
191  void setObjCGCAttr(GC type) {
192    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
193  }
194  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
195  void addObjCGCAttr(GC type) {
196    assert(type);
197    setObjCGCAttr(type);
198  }
199
200  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
201  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
202  void setAddressSpace(unsigned space) {
203    assert(space <= MaxAddressSpace);
204    Mask = (Mask & ~AddressSpaceMask)
205         | (((uint32_t) space) << AddressSpaceShift);
206  }
207  void removeAddressSpace() { setAddressSpace(0); }
208  void addAddressSpace(unsigned space) {
209    assert(space);
210    setAddressSpace(space);
211  }
212
213  // Fast qualifiers are those that can be allocated directly
214  // on a QualType object.
215  bool hasFastQualifiers() const { return getFastQualifiers(); }
216  unsigned getFastQualifiers() const { return Mask & FastMask; }
217  void setFastQualifiers(unsigned mask) {
218    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
219    Mask = (Mask & ~FastMask) | mask;
220  }
221  void removeFastQualifiers(unsigned mask) {
222    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
223    Mask &= ~mask;
224  }
225  void removeFastQualifiers() {
226    removeFastQualifiers(FastMask);
227  }
228  void addFastQualifiers(unsigned mask) {
229    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
230    Mask |= mask;
231  }
232
233  /// hasNonFastQualifiers - Return true if the set contains any
234  /// qualifiers which require an ExtQuals node to be allocated.
235  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
236  Qualifiers getNonFastQualifiers() const {
237    Qualifiers Quals = *this;
238    Quals.setFastQualifiers(0);
239    return Quals;
240  }
241
242  /// hasQualifiers - Return true if the set contains any qualifiers.
243  bool hasQualifiers() const { return Mask; }
244  bool empty() const { return !Mask; }
245
246  /// \brief Add the qualifiers from the given set to this set.
247  void addQualifiers(Qualifiers Q) {
248    // If the other set doesn't have any non-boolean qualifiers, just
249    // bit-or it in.
250    if (!(Q.Mask & ~CVRMask))
251      Mask |= Q.Mask;
252    else {
253      Mask |= (Q.Mask & CVRMask);
254      if (Q.hasAddressSpace())
255        addAddressSpace(Q.getAddressSpace());
256      if (Q.hasObjCGCAttr())
257        addObjCGCAttr(Q.getObjCGCAttr());
258    }
259  }
260
261  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
262  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
263
264  operator bool() const { return hasQualifiers(); }
265
266  Qualifiers &operator+=(Qualifiers R) {
267    addQualifiers(R);
268    return *this;
269  }
270
271  // Union two qualifier sets.  If an enumerated qualifier appears
272  // in both sets, use the one from the right.
273  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
274    L += R;
275    return L;
276  }
277
278  std::string getAsString() const;
279  std::string getAsString(const PrintingPolicy &Policy) const {
280    std::string Buffer;
281    getAsStringInternal(Buffer, Policy);
282    return Buffer;
283  }
284  void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
285
286  void Profile(llvm::FoldingSetNodeID &ID) const {
287    ID.AddInteger(Mask);
288  }
289
290private:
291
292  // bits:     |0 1 2|3 .. 4|5  ..  31|
293  //           |C R V|GCAttr|AddrSpace|
294  uint32_t Mask;
295
296  static const uint32_t GCAttrMask = 0x18;
297  static const uint32_t GCAttrShift = 3;
298  static const uint32_t AddressSpaceMask = ~(CVRMask | GCAttrMask);
299  static const uint32_t AddressSpaceShift = 5;
300};
301
302
303/// ExtQuals - We can encode up to three bits in the low bits of a
304/// type pointer, but there are many more type qualifiers that we want
305/// to be able to apply to an arbitrary type.  Therefore we have this
306/// struct, intended to be heap-allocated and used by QualType to
307/// store qualifiers.
308///
309/// The current design tags the 'const' and 'restrict' qualifiers in
310/// two low bits on the QualType pointer; a third bit records whether
311/// the pointer is an ExtQuals node.  'const' was chosen because it is
312/// orders of magnitude more common than the other two qualifiers, in
313/// both library and user code.  It's relatively rare to see
314/// 'restrict' in user code, but many standard C headers are saturated
315/// with 'restrict' declarations, so that representing them efficiently
316/// is a critical goal of this representation.
317class ExtQuals : public llvm::FoldingSetNode {
318  // NOTE: changing the fast qualifiers should be straightforward as
319  // long as you don't make 'const' non-fast.
320  // 1. Qualifiers:
321  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
322  //       Fast qualifiers must occupy the low-order bits.
323  //    b) Update Qualifiers::FastWidth and FastMask.
324  // 2. QualType:
325  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
326  //    b) Update remove{Volatile,Restrict}, defined near the end of
327  //       this header.
328  // 3. ASTContext:
329  //    a) Update get{Volatile,Restrict}Type.
330
331  /// Context - the context to which this set belongs.  We save this
332  /// here so that QualifierCollector can use it to reapply extended
333  /// qualifiers to an arbitrary type without requiring a context to
334  /// be pushed through every single API dealing with qualifiers.
335  ASTContext& Context;
336
337  /// BaseType - the underlying type that this qualifies
338  const Type *BaseType;
339
340  /// Quals - the immutable set of qualifiers applied by this
341  /// node;  always contains extended qualifiers.
342  Qualifiers Quals;
343
344public:
345  ExtQuals(ASTContext& Context, const Type *Base, Qualifiers Quals)
346    : Context(Context), BaseType(Base), Quals(Quals)
347  {
348    assert(Quals.hasNonFastQualifiers()
349           && "ExtQuals created with no fast qualifiers");
350    assert(!Quals.hasFastQualifiers()
351           && "ExtQuals created with fast qualifiers");
352  }
353
354  Qualifiers getQualifiers() const { return Quals; }
355
356  bool hasVolatile() const { return Quals.hasVolatile(); }
357
358  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
359  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
360
361  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
362  unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
363
364  const Type *getBaseType() const { return BaseType; }
365
366  ASTContext &getContext() const { return Context; }
367
368public:
369  void Profile(llvm::FoldingSetNodeID &ID) const {
370    Profile(ID, getBaseType(), Quals);
371  }
372  static void Profile(llvm::FoldingSetNodeID &ID,
373                      const Type *BaseType,
374                      Qualifiers Quals) {
375    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
376    ID.AddPointer(BaseType);
377    Quals.Profile(ID);
378  }
379};
380
381
382/// QualType - For efficiency, we don't store CV-qualified types as nodes on
383/// their own: instead each reference to a type stores the qualifiers.  This
384/// greatly reduces the number of nodes we need to allocate for types (for
385/// example we only need one for 'int', 'const int', 'volatile int',
386/// 'const volatile int', etc).
387///
388/// As an added efficiency bonus, instead of making this a pair, we
389/// just store the two bits we care about in the low bits of the
390/// pointer.  To handle the packing/unpacking, we make QualType be a
391/// simple wrapper class that acts like a smart pointer.  A third bit
392/// indicates whether there are extended qualifiers present, in which
393/// case the pointer points to a special structure.
394class QualType {
395  // Thankfully, these are efficiently composable.
396  llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
397                       Qualifiers::FastWidth> Value;
398
399  bool hasExtQuals() const {
400    return Value.getPointer().is<const ExtQuals*>();
401  }
402
403  const ExtQuals *getExtQualsUnsafe() const {
404    return Value.getPointer().get<const ExtQuals*>();
405  }
406
407  const Type *getTypePtrUnsafe() const {
408    return Value.getPointer().get<const Type*>();
409  }
410
411  friend class QualifierCollector;
412public:
413  QualType() {}
414
415  QualType(const Type *Ptr, unsigned Quals)
416    : Value(Ptr, Quals) {}
417  QualType(const ExtQuals *Ptr, unsigned Quals)
418    : Value(Ptr, Quals) {}
419
420  unsigned getFastQualifiers() const { return Value.getInt(); }
421  void setFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
422
423  /// Retrieves a pointer to the underlying (unqualified) type.
424  /// This should really return a const Type, but it's not worth
425  /// changing all the users right now.
426  Type *getTypePtr() const {
427    if (hasNonFastQualifiers())
428      return const_cast<Type*>(getExtQualsUnsafe()->getBaseType());
429    return const_cast<Type*>(getTypePtrUnsafe());
430  }
431
432  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
433  static QualType getFromOpaquePtr(void *Ptr) {
434    QualType T;
435    T.Value.setFromOpaqueValue(Ptr);
436    return T;
437  }
438
439  Type &operator*() const {
440    return *getTypePtr();
441  }
442
443  Type *operator->() const {
444    return getTypePtr();
445  }
446
447  bool isCanonical() const;
448  bool isCanonicalAsParam() const;
449
450  /// isNull - Return true if this QualType doesn't point to a type yet.
451  bool isNull() const {
452    return Value.getPointer().isNull();
453  }
454
455  bool isConstQualified() const {
456    return (getFastQualifiers() & Qualifiers::Const);
457  }
458  bool isRestrictQualified() const {
459    return (getFastQualifiers() & Qualifiers::Restrict);
460  }
461  bool isVolatileQualified() const {
462    return (hasNonFastQualifiers() && getExtQualsUnsafe()->hasVolatile());
463  }
464
465  // Determines whether this type has any direct qualifiers.
466  bool hasQualifiers() const {
467    return getFastQualifiers() || hasNonFastQualifiers();
468  }
469
470  bool hasNonFastQualifiers() const {
471    return hasExtQuals();
472  }
473
474  // Retrieves the set of qualifiers belonging to this type.
475  Qualifiers getQualifiers() const {
476    Qualifiers Quals;
477    if (hasNonFastQualifiers())
478      Quals = getExtQualsUnsafe()->getQualifiers();
479    Quals.addFastQualifiers(getFastQualifiers());
480    return Quals;
481  }
482
483  // Retrieves the CVR qualifiers of this type.
484  unsigned getCVRQualifiers() const {
485    unsigned CVR = getFastQualifiers();
486    if (isVolatileQualified()) CVR |= Qualifiers::Volatile;
487    return CVR;
488  }
489
490  bool isConstant(ASTContext& Ctx) const {
491    return QualType::isConstant(*this, Ctx);
492  }
493
494  // Don't promise in the API that anything besides 'const' can be
495  // easily added.
496
497  /// addConst - add the specified type qualifier to this QualType.
498  void addConst() {
499    addFastQualifiers(Qualifiers::Const);
500  }
501  QualType withConst() const {
502    return withFastQualifiers(Qualifiers::Const);
503  }
504
505  void addFastQualifiers(unsigned TQs) {
506    assert(!(TQs & ~Qualifiers::FastMask)
507           && "non-fast qualifier bits set in mask!");
508    Value.setInt(Value.getInt() | TQs);
509  }
510
511  void removeConst();
512  void removeVolatile();
513  void removeRestrict();
514  void removeCVRQualifiers(unsigned Mask);
515
516  void removeFastQualifiers() { Value.setInt(0); }
517  void removeFastQualifiers(unsigned Mask) {
518    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
519    Value.setInt(Value.getInt() & ~Mask);
520  }
521
522  // Creates a type with the given qualifiers in addition to any
523  // qualifiers already on this type.
524  QualType withFastQualifiers(unsigned TQs) const {
525    QualType T = *this;
526    T.addFastQualifiers(TQs);
527    return T;
528  }
529
530  // Creates a type with exactly the given fast qualifiers, removing
531  // any existing fast qualifiers.
532  QualType withExactFastQualifiers(unsigned TQs) const {
533    return withoutFastQualifiers().withFastQualifiers(TQs);
534  }
535
536  // Removes fast qualifiers, but leaves any extended qualifiers in place.
537  QualType withoutFastQualifiers() const {
538    QualType T = *this;
539    T.removeFastQualifiers();
540    return T;
541  }
542
543  QualType getUnqualifiedType() const { return QualType(getTypePtr(), 0); }
544
545  bool isMoreQualifiedThan(QualType Other) const;
546  bool isAtLeastAsQualifiedAs(QualType Other) const;
547  QualType getNonReferenceType() const;
548
549  /// getDesugaredType - Return the specified type with any "sugar" removed from
550  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
551  /// the type is already concrete, it returns it unmodified.  This is similar
552  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
553  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
554  /// concrete.
555  ///
556  /// Qualifiers are left in place.
557  QualType getDesugaredType() const {
558    return QualType::getDesugaredType(*this);
559  }
560
561  /// operator==/!= - Indicate whether the specified types and qualifiers are
562  /// identical.
563  friend bool operator==(const QualType &LHS, const QualType &RHS) {
564    return LHS.Value == RHS.Value;
565  }
566  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
567    return LHS.Value != RHS.Value;
568  }
569  std::string getAsString() const;
570
571  std::string getAsString(const PrintingPolicy &Policy) const {
572    std::string S;
573    getAsStringInternal(S, Policy);
574    return S;
575  }
576  void getAsStringInternal(std::string &Str,
577                           const PrintingPolicy &Policy) const;
578
579  void dump(const char *s) const;
580  void dump() const;
581
582  void Profile(llvm::FoldingSetNodeID &ID) const {
583    ID.AddPointer(getAsOpaquePtr());
584  }
585
586  /// getAddressSpace - Return the address space of this type.
587  inline unsigned getAddressSpace() const;
588
589  /// GCAttrTypesAttr - Returns gc attribute of this type.
590  inline Qualifiers::GC getObjCGCAttr() const;
591
592  /// isObjCGCWeak true when Type is objc's weak.
593  bool isObjCGCWeak() const {
594    return getObjCGCAttr() == Qualifiers::Weak;
595  }
596
597  /// isObjCGCStrong true when Type is objc's strong.
598  bool isObjCGCStrong() const {
599    return getObjCGCAttr() == Qualifiers::Strong;
600  }
601
602  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
603  /// false otherwise.
604  bool getNoReturnAttr() const;
605
606private:
607  // These methods are implemented in a separate translation unit;
608  // "static"-ize them to avoid creating temporary QualTypes in the
609  // caller.
610  static bool isConstant(QualType T, ASTContext& Ctx);
611  static QualType getDesugaredType(QualType T);
612};
613
614} // end clang.
615
616namespace llvm {
617/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
618/// to a specific Type class.
619template<> struct simplify_type<const ::clang::QualType> {
620  typedef ::clang::Type* SimpleType;
621  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
622    return Val.getTypePtr();
623  }
624};
625template<> struct simplify_type< ::clang::QualType>
626  : public simplify_type<const ::clang::QualType> {};
627
628// Teach SmallPtrSet that QualType is "basically a pointer".
629template<>
630class PointerLikeTypeTraits<clang::QualType> {
631public:
632  static inline void *getAsVoidPointer(clang::QualType P) {
633    return P.getAsOpaquePtr();
634  }
635  static inline clang::QualType getFromVoidPointer(void *P) {
636    return clang::QualType::getFromOpaquePtr(P);
637  }
638  // Various qualifiers go in low bits.
639  enum { NumLowBitsAvailable = 0 };
640};
641
642} // end namespace llvm
643
644namespace clang {
645
646/// Type - This is the base class of the type hierarchy.  A central concept
647/// with types is that each type always has a canonical type.  A canonical type
648/// is the type with any typedef names stripped out of it or the types it
649/// references.  For example, consider:
650///
651///  typedef int  foo;
652///  typedef foo* bar;
653///    'int *'    'foo *'    'bar'
654///
655/// There will be a Type object created for 'int'.  Since int is canonical, its
656/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
657/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
658/// there is a PointerType that represents 'int*', which, like 'int', is
659/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
660/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
661/// is also 'int*'.
662///
663/// Non-canonical types are useful for emitting diagnostics, without losing
664/// information about typedefs being used.  Canonical types are useful for type
665/// comparisons (they allow by-pointer equality tests) and useful for reasoning
666/// about whether something has a particular form (e.g. is a function type),
667/// because they implicitly, recursively, strip all typedefs out of a type.
668///
669/// Types, once created, are immutable.
670///
671class Type {
672public:
673  enum TypeClass {
674#define TYPE(Class, Base) Class,
675#define ABSTRACT_TYPE(Class, Base)
676#include "clang/AST/TypeNodes.def"
677    TagFirst = Record, TagLast = Enum
678  };
679
680protected:
681  enum { TypeClassBitSize = 6 };
682
683private:
684  QualType CanonicalType;
685
686  /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
687  bool Dependent : 1;
688
689  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
690  /// Note that this should stay at the end of the ivars for Type so that
691  /// subclasses can pack their bitfields into the same word.
692  unsigned TC : TypeClassBitSize;
693
694  Type(const Type&);           // DO NOT IMPLEMENT.
695  void operator=(const Type&); // DO NOT IMPLEMENT.
696protected:
697  // silence VC++ warning C4355: 'this' : used in base member initializer list
698  Type *this_() { return this; }
699  Type(TypeClass tc, QualType Canonical, bool dependent)
700    : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical),
701      Dependent(dependent), TC(tc) {}
702  virtual ~Type() {}
703  virtual void Destroy(ASTContext& C);
704  friend class ASTContext;
705
706public:
707  TypeClass getTypeClass() const { return static_cast<TypeClass>(TC); }
708
709  bool isCanonicalUnqualified() const {
710    return CanonicalType.getTypePtr() == this;
711  }
712
713  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
714  /// object types, function types, and incomplete types.
715
716  /// \brief Determines whether the type describes an object in memory.
717  ///
718  /// Note that this definition of object type corresponds to the C++
719  /// definition of object type, which includes incomplete types, as
720  /// opposed to the C definition (which does not include incomplete
721  /// types).
722  bool isObjectType() const;
723
724  /// isIncompleteType - Return true if this is an incomplete type.
725  /// A type that can describe objects, but which lacks information needed to
726  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
727  /// routine will need to determine if the size is actually required.
728  bool isIncompleteType() const;
729
730  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
731  /// type, in other words, not a function type.
732  bool isIncompleteOrObjectType() const {
733    return !isFunctionType();
734  }
735
736  /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10).
737  bool isPODType() const;
738
739  /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array
740  /// types that have a non-constant expression. This does not include "[]".
741  bool isVariablyModifiedType() const;
742
743  /// Helper methods to distinguish type categories. All type predicates
744  /// operate on the canonical type, ignoring typedefs and qualifiers.
745
746  /// isSpecificBuiltinType - Test for a particular builtin type.
747  bool isSpecificBuiltinType(unsigned K) const;
748
749  /// isIntegerType() does *not* include complex integers (a GCC extension).
750  /// isComplexIntegerType() can be used to test for complex integers.
751  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
752  bool isEnumeralType() const;
753  bool isBooleanType() const;
754  bool isCharType() const;
755  bool isWideCharType() const;
756  bool isIntegralType() const;
757
758  /// Floating point categories.
759  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
760  /// isComplexType() does *not* include complex integers (a GCC extension).
761  /// isComplexIntegerType() can be used to test for complex integers.
762  bool isComplexType() const;      // C99 6.2.5p11 (complex)
763  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
764  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
765  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
766  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
767  bool isVoidType() const;         // C99 6.2.5p19
768  bool isDerivedType() const;      // C99 6.2.5p20
769  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
770  bool isAggregateType() const;
771
772  // Type Predicates: Check to see if this type is structurally the specified
773  // type, ignoring typedefs and qualifiers.
774  bool isFunctionType() const;
775  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
776  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
777  bool isPointerType() const;
778  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
779  bool isBlockPointerType() const;
780  bool isVoidPointerType() const;
781  bool isReferenceType() const;
782  bool isLValueReferenceType() const;
783  bool isRValueReferenceType() const;
784  bool isFunctionPointerType() const;
785  bool isMemberPointerType() const;
786  bool isMemberFunctionPointerType() const;
787  bool isArrayType() const;
788  bool isConstantArrayType() const;
789  bool isIncompleteArrayType() const;
790  bool isVariableArrayType() const;
791  bool isDependentSizedArrayType() const;
792  bool isRecordType() const;
793  bool isClassType() const;
794  bool isStructureType() const;
795  bool isUnionType() const;
796  bool isComplexIntegerType() const;            // GCC _Complex integer type.
797  bool isVectorType() const;                    // GCC vector type.
798  bool isExtVectorType() const;                 // Extended vector type.
799  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
800  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
801  // for the common case.
802  bool isObjCInterfaceType() const;             // NSString or NSString<foo>
803  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
804  bool isObjCQualifiedIdType() const;           // id<foo>
805  bool isObjCQualifiedClassType() const;        // Class<foo>
806  bool isObjCIdType() const;                    // id
807  bool isObjCClassType() const;                 // Class
808  bool isObjCBuiltinType() const;               // 'id' or 'Class'
809  bool isTemplateTypeParmType() const;          // C++ template type parameter
810  bool isNullPtrType() const;                   // C++0x nullptr_t
811
812  /// isDependentType - Whether this type is a dependent type, meaning
813  /// that its definition somehow depends on a template parameter
814  /// (C++ [temp.dep.type]).
815  bool isDependentType() const { return Dependent; }
816  bool isOverloadableType() const;
817
818  /// hasPointerRepresentation - Whether this type is represented
819  /// natively as a pointer; this includes pointers, references, block
820  /// pointers, and Objective-C interface, qualified id, and qualified
821  /// interface types, as well as nullptr_t.
822  bool hasPointerRepresentation() const;
823
824  /// hasObjCPointerRepresentation - Whether this type can represent
825  /// an objective pointer type for the purpose of GC'ability
826  bool hasObjCPointerRepresentation() const;
827
828  // Type Checking Functions: Check to see if this type is structurally the
829  // specified type, ignoring typedefs and qualifiers, and return a pointer to
830  // the best type we can.
831  const RecordType *getAsStructureType() const;
832  /// NOTE: getAs*ArrayType are methods on ASTContext.
833  const RecordType *getAsUnionType() const;
834  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
835  // The following is a convenience method that returns an ObjCObjectPointerType
836  // for object declared using an interface.
837  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
838  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
839  const ObjCInterfaceType *getAsObjCQualifiedInterfaceType() const;
840  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
841
842  // Member-template getAs<specific type>'.  This scheme will eventually
843  // replace the specific getAsXXXX methods above.
844  //
845  // There are some specializations of this member template listed
846  // immediately following this class.
847  template <typename T> const T *getAs() const;
848
849  /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC
850  /// interface, return the interface type, otherwise return null.
851  const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const;
852
853  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
854  /// element type of the array, potentially with type qualifiers missing.
855  /// This method should never be used when type qualifiers are meaningful.
856  const Type *getArrayElementTypeNoTypeQual() const;
857
858  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
859  /// pointer, this returns the respective pointee.
860  QualType getPointeeType() const;
861
862  /// getUnqualifiedDesugaredType() - Return the specified type with
863  /// any "sugar" removed from the type, removing any typedefs,
864  /// typeofs, etc., as well as any qualifiers.
865  const Type *getUnqualifiedDesugaredType() const;
866
867  /// More type predicates useful for type checking/promotion
868  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
869
870  /// isSignedIntegerType - Return true if this is an integer type that is
871  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
872  /// an enum decl which has a signed representation, or a vector of signed
873  /// integer element type.
874  bool isSignedIntegerType() const;
875
876  /// isUnsignedIntegerType - Return true if this is an integer type that is
877  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
878  /// decl which has an unsigned representation, or a vector of unsigned integer
879  /// element type.
880  bool isUnsignedIntegerType() const;
881
882  /// isConstantSizeType - Return true if this is not a variable sized type,
883  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
884  /// incomplete types.
885  bool isConstantSizeType() const;
886
887  /// isSpecifierType - Returns true if this type can be represented by some
888  /// set of type specifiers.
889  bool isSpecifierType() const;
890
891  const char *getTypeClassName() const;
892
893  QualType getCanonicalTypeInternal() const { return CanonicalType; }
894  void dump() const;
895  virtual void getAsStringInternal(std::string &InnerString,
896                                   const PrintingPolicy &Policy) const = 0;
897  static bool classof(const Type *) { return true; }
898};
899
900template <> inline const TypedefType *Type::getAs() const {
901  return dyn_cast<TypedefType>(this);
902}
903
904// We can do canonical leaf types faster, because we don't have to
905// worry about preserving child type decoration.
906#define TYPE(Class, Base)
907#define LEAF_TYPE(Class) \
908template <> inline const Class##Type *Type::getAs() const { \
909  return dyn_cast<Class##Type>(CanonicalType); \
910}
911#include "clang/AST/TypeNodes.def"
912
913
914/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
915/// types are always canonical and have a literal name field.
916class BuiltinType : public Type {
917public:
918  enum Kind {
919    Void,
920
921    Bool,     // This is bool and/or _Bool.
922    Char_U,   // This is 'char' for targets where char is unsigned.
923    UChar,    // This is explicitly qualified unsigned char.
924    Char16,   // This is 'char16_t' for C++.
925    Char32,   // This is 'char32_t' for C++.
926    UShort,
927    UInt,
928    ULong,
929    ULongLong,
930    UInt128,  // __uint128_t
931
932    Char_S,   // This is 'char' for targets where char is signed.
933    SChar,    // This is explicitly qualified signed char.
934    WChar,    // This is 'wchar_t' for C++.
935    Short,
936    Int,
937    Long,
938    LongLong,
939    Int128,   // __int128_t
940
941    Float, Double, LongDouble,
942
943    NullPtr,  // This is the type of C++0x 'nullptr'.
944
945    Overload,  // This represents the type of an overloaded function declaration.
946    Dependent, // This represents the type of a type-dependent expression.
947
948    UndeducedAuto, // In C++0x, this represents the type of an auto variable
949                   // that has not been deduced yet.
950    ObjCId,    // This represents the ObjC 'id' type.
951    ObjCClass  // This represents the ObjC 'Class' type.
952  };
953private:
954  Kind TypeKind;
955public:
956  BuiltinType(Kind K)
957    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
958      TypeKind(K) {}
959
960  Kind getKind() const { return TypeKind; }
961  const char *getName(const LangOptions &LO) const;
962
963  bool isSugared() const { return false; }
964  QualType desugar() const { return QualType(this, 0); }
965
966  bool isInteger() const {
967    return TypeKind >= Bool && TypeKind <= Int128;
968  }
969
970  bool isSignedInteger() const {
971    return TypeKind >= Char_S && TypeKind <= Int128;
972  }
973
974  bool isUnsignedInteger() const {
975    return TypeKind >= Bool && TypeKind <= UInt128;
976  }
977
978  bool isFloatingPoint() const {
979    return TypeKind >= Float && TypeKind <= LongDouble;
980  }
981
982  virtual void getAsStringInternal(std::string &InnerString,
983                                   const PrintingPolicy &Policy) const;
984
985  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
986  static bool classof(const BuiltinType *) { return true; }
987};
988
989/// FixedWidthIntType - Used for arbitrary width types that we either don't
990/// want to or can't map to named integer types.  These always have a lower
991/// integer rank than builtin types of the same width.
992class FixedWidthIntType : public Type {
993private:
994  unsigned Width;
995  bool Signed;
996public:
997  FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false),
998                                          Width(W), Signed(S) {}
999
1000  unsigned getWidth() const { return Width; }
1001  bool isSigned() const { return Signed; }
1002  const char *getName() const;
1003
1004  bool isSugared() const { return false; }
1005  QualType desugar() const { return QualType(this, 0); }
1006
1007  virtual void getAsStringInternal(std::string &InnerString,
1008                                   const PrintingPolicy &Policy) const;
1009
1010  static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; }
1011  static bool classof(const FixedWidthIntType *) { return true; }
1012};
1013
1014/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1015/// types (_Complex float etc) as well as the GCC integer complex extensions.
1016///
1017class ComplexType : public Type, public llvm::FoldingSetNode {
1018  QualType ElementType;
1019  ComplexType(QualType Element, QualType CanonicalPtr) :
1020    Type(Complex, CanonicalPtr, Element->isDependentType()),
1021    ElementType(Element) {
1022  }
1023  friend class ASTContext;  // ASTContext creates these.
1024public:
1025  QualType getElementType() const { return ElementType; }
1026
1027  virtual void getAsStringInternal(std::string &InnerString,
1028                                   const PrintingPolicy &Policy) const;
1029
1030  bool isSugared() const { return false; }
1031  QualType desugar() const { return QualType(this, 0); }
1032
1033  void Profile(llvm::FoldingSetNodeID &ID) {
1034    Profile(ID, getElementType());
1035  }
1036  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1037    ID.AddPointer(Element.getAsOpaquePtr());
1038  }
1039
1040  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1041  static bool classof(const ComplexType *) { return true; }
1042};
1043
1044/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1045///
1046class PointerType : public Type, public llvm::FoldingSetNode {
1047  QualType PointeeType;
1048
1049  PointerType(QualType Pointee, QualType CanonicalPtr) :
1050    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1051  }
1052  friend class ASTContext;  // ASTContext creates these.
1053public:
1054
1055  virtual void getAsStringInternal(std::string &InnerString,
1056                                   const PrintingPolicy &Policy) const;
1057
1058  QualType getPointeeType() const { return PointeeType; }
1059
1060  bool isSugared() const { return false; }
1061  QualType desugar() const { return QualType(this, 0); }
1062
1063  void Profile(llvm::FoldingSetNodeID &ID) {
1064    Profile(ID, getPointeeType());
1065  }
1066  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1067    ID.AddPointer(Pointee.getAsOpaquePtr());
1068  }
1069
1070  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1071  static bool classof(const PointerType *) { return true; }
1072};
1073
1074/// BlockPointerType - pointer to a block type.
1075/// This type is to represent types syntactically represented as
1076/// "void (^)(int)", etc. Pointee is required to always be a function type.
1077///
1078class BlockPointerType : public Type, public llvm::FoldingSetNode {
1079  QualType PointeeType;  // Block is some kind of pointer type
1080  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1081    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1082    PointeeType(Pointee) {
1083  }
1084  friend class ASTContext;  // ASTContext creates these.
1085public:
1086
1087  // Get the pointee type. Pointee is required to always be a function type.
1088  QualType getPointeeType() const { return PointeeType; }
1089
1090  virtual void getAsStringInternal(std::string &InnerString,
1091                                   const PrintingPolicy &Policy) const;
1092
1093  bool isSugared() const { return false; }
1094  QualType desugar() const { return QualType(this, 0); }
1095
1096  void Profile(llvm::FoldingSetNodeID &ID) {
1097      Profile(ID, getPointeeType());
1098  }
1099  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1100      ID.AddPointer(Pointee.getAsOpaquePtr());
1101  }
1102
1103  static bool classof(const Type *T) {
1104    return T->getTypeClass() == BlockPointer;
1105  }
1106  static bool classof(const BlockPointerType *) { return true; }
1107};
1108
1109/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1110///
1111class ReferenceType : public Type, public llvm::FoldingSetNode {
1112  QualType PointeeType;
1113
1114  /// True if the type was originally spelled with an lvalue sigil.
1115  /// This is never true of rvalue references but can also be false
1116  /// on lvalue references because of C++0x [dcl.typedef]p9,
1117  /// as follows:
1118  ///
1119  ///   typedef int &ref;    // lvalue, spelled lvalue
1120  ///   typedef int &&rvref; // rvalue
1121  ///   ref &a;              // lvalue, inner ref, spelled lvalue
1122  ///   ref &&a;             // lvalue, inner ref
1123  ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1124  ///   rvref &&a;           // rvalue, inner ref
1125  bool SpelledAsLValue;
1126
1127  /// True if the inner type is a reference type.  This only happens
1128  /// in non-canonical forms.
1129  bool InnerRef;
1130
1131protected:
1132  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1133                bool SpelledAsLValue) :
1134    Type(tc, CanonicalRef, Referencee->isDependentType()),
1135    PointeeType(Referencee), SpelledAsLValue(SpelledAsLValue),
1136    InnerRef(Referencee->isReferenceType()) {
1137  }
1138public:
1139  bool isSpelledAsLValue() const { return SpelledAsLValue; }
1140
1141  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1142  QualType getPointeeType() const {
1143    // FIXME: this might strip inner qualifiers; okay?
1144    const ReferenceType *T = this;
1145    while (T->InnerRef)
1146      T = T->PointeeType->getAs<ReferenceType>();
1147    return T->PointeeType;
1148  }
1149
1150  void Profile(llvm::FoldingSetNodeID &ID) {
1151    Profile(ID, PointeeType, SpelledAsLValue);
1152  }
1153  static void Profile(llvm::FoldingSetNodeID &ID,
1154                      QualType Referencee,
1155                      bool SpelledAsLValue) {
1156    ID.AddPointer(Referencee.getAsOpaquePtr());
1157    ID.AddBoolean(SpelledAsLValue);
1158  }
1159
1160  static bool classof(const Type *T) {
1161    return T->getTypeClass() == LValueReference ||
1162           T->getTypeClass() == RValueReference;
1163  }
1164  static bool classof(const ReferenceType *) { return true; }
1165};
1166
1167/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1168///
1169class LValueReferenceType : public ReferenceType {
1170  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1171                      bool SpelledAsLValue) :
1172    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1173  {}
1174  friend class ASTContext; // ASTContext creates these
1175public:
1176  virtual void getAsStringInternal(std::string &InnerString,
1177                                   const PrintingPolicy &Policy) const;
1178
1179  bool isSugared() const { return false; }
1180  QualType desugar() const { return QualType(this, 0); }
1181
1182  static bool classof(const Type *T) {
1183    return T->getTypeClass() == LValueReference;
1184  }
1185  static bool classof(const LValueReferenceType *) { return true; }
1186};
1187
1188/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1189///
1190class RValueReferenceType : public ReferenceType {
1191  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1192    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1193  }
1194  friend class ASTContext; // ASTContext creates these
1195public:
1196  virtual void getAsStringInternal(std::string &InnerString,
1197                                   const PrintingPolicy &Policy) const;
1198
1199  bool isSugared() const { return false; }
1200  QualType desugar() const { return QualType(this, 0); }
1201
1202  static bool classof(const Type *T) {
1203    return T->getTypeClass() == RValueReference;
1204  }
1205  static bool classof(const RValueReferenceType *) { return true; }
1206};
1207
1208/// MemberPointerType - C++ 8.3.3 - Pointers to members
1209///
1210class MemberPointerType : public Type, public llvm::FoldingSetNode {
1211  QualType PointeeType;
1212  /// The class of which the pointee is a member. Must ultimately be a
1213  /// RecordType, but could be a typedef or a template parameter too.
1214  const Type *Class;
1215
1216  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1217    Type(MemberPointer, CanonicalPtr,
1218         Cls->isDependentType() || Pointee->isDependentType()),
1219    PointeeType(Pointee), Class(Cls) {
1220  }
1221  friend class ASTContext; // ASTContext creates these.
1222public:
1223
1224  QualType getPointeeType() const { return PointeeType; }
1225
1226  const Type *getClass() const { return Class; }
1227
1228  virtual void getAsStringInternal(std::string &InnerString,
1229                                   const PrintingPolicy &Policy) const;
1230
1231  bool isSugared() const { return false; }
1232  QualType desugar() const { return QualType(this, 0); }
1233
1234  void Profile(llvm::FoldingSetNodeID &ID) {
1235    Profile(ID, getPointeeType(), getClass());
1236  }
1237  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1238                      const Type *Class) {
1239    ID.AddPointer(Pointee.getAsOpaquePtr());
1240    ID.AddPointer(Class);
1241  }
1242
1243  static bool classof(const Type *T) {
1244    return T->getTypeClass() == MemberPointer;
1245  }
1246  static bool classof(const MemberPointerType *) { return true; }
1247};
1248
1249/// ArrayType - C99 6.7.5.2 - Array Declarators.
1250///
1251class ArrayType : public Type, public llvm::FoldingSetNode {
1252public:
1253  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1254  /// an array with a static size (e.g. int X[static 4]), or an array
1255  /// with a star size (e.g. int X[*]).
1256  /// 'static' is only allowed on function parameters.
1257  enum ArraySizeModifier {
1258    Normal, Static, Star
1259  };
1260private:
1261  /// ElementType - The element type of the array.
1262  QualType ElementType;
1263
1264  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1265  /// NOTE: These fields are packed into the bitfields space in the Type class.
1266  unsigned SizeModifier : 2;
1267
1268  /// IndexTypeQuals - Capture qualifiers in declarations like:
1269  /// 'int X[static restrict 4]'. For function parameters only.
1270  unsigned IndexTypeQuals : 3;
1271
1272protected:
1273  // C++ [temp.dep.type]p1:
1274  //   A type is dependent if it is...
1275  //     - an array type constructed from any dependent type or whose
1276  //       size is specified by a constant expression that is
1277  //       value-dependent,
1278  ArrayType(TypeClass tc, QualType et, QualType can,
1279            ArraySizeModifier sm, unsigned tq)
1280    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1281      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1282
1283  friend class ASTContext;  // ASTContext creates these.
1284public:
1285  QualType getElementType() const { return ElementType; }
1286  ArraySizeModifier getSizeModifier() const {
1287    return ArraySizeModifier(SizeModifier);
1288  }
1289  Qualifiers getIndexTypeQualifiers() const {
1290    return Qualifiers::fromCVRMask(IndexTypeQuals);
1291  }
1292  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1293
1294  static bool classof(const Type *T) {
1295    return T->getTypeClass() == ConstantArray ||
1296           T->getTypeClass() == VariableArray ||
1297           T->getTypeClass() == IncompleteArray ||
1298           T->getTypeClass() == DependentSizedArray;
1299  }
1300  static bool classof(const ArrayType *) { return true; }
1301};
1302
1303/// ConstantArrayType - This class represents the canonical version of
1304/// C arrays with a specified constant size.  For example, the canonical
1305/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1306/// type is 'int' and the size is 404.
1307class ConstantArrayType : public ArrayType {
1308  llvm::APInt Size; // Allows us to unique the type.
1309
1310  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1311                    ArraySizeModifier sm, unsigned tq)
1312    : ArrayType(ConstantArray, et, can, sm, tq),
1313      Size(size) {}
1314protected:
1315  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1316                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1317    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1318  friend class ASTContext;  // ASTContext creates these.
1319public:
1320  const llvm::APInt &getSize() const { return Size; }
1321  virtual void getAsStringInternal(std::string &InnerString,
1322                                   const PrintingPolicy &Policy) const;
1323
1324  bool isSugared() const { return false; }
1325  QualType desugar() const { return QualType(this, 0); }
1326
1327  void Profile(llvm::FoldingSetNodeID &ID) {
1328    Profile(ID, getElementType(), getSize(),
1329            getSizeModifier(), getIndexTypeCVRQualifiers());
1330  }
1331  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1332                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1333                      unsigned TypeQuals) {
1334    ID.AddPointer(ET.getAsOpaquePtr());
1335    ID.AddInteger(ArraySize.getZExtValue());
1336    ID.AddInteger(SizeMod);
1337    ID.AddInteger(TypeQuals);
1338  }
1339  static bool classof(const Type *T) {
1340    return T->getTypeClass() == ConstantArray;
1341  }
1342  static bool classof(const ConstantArrayType *) { return true; }
1343};
1344
1345/// IncompleteArrayType - This class represents C arrays with an unspecified
1346/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1347/// type is 'int' and the size is unspecified.
1348class IncompleteArrayType : public ArrayType {
1349
1350  IncompleteArrayType(QualType et, QualType can,
1351                      ArraySizeModifier sm, unsigned tq)
1352    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1353  friend class ASTContext;  // ASTContext creates these.
1354public:
1355  virtual void getAsStringInternal(std::string &InnerString,
1356                                   const PrintingPolicy &Policy) const;
1357
1358  bool isSugared() const { return false; }
1359  QualType desugar() const { return QualType(this, 0); }
1360
1361  static bool classof(const Type *T) {
1362    return T->getTypeClass() == IncompleteArray;
1363  }
1364  static bool classof(const IncompleteArrayType *) { return true; }
1365
1366  friend class StmtIteratorBase;
1367
1368  void Profile(llvm::FoldingSetNodeID &ID) {
1369    Profile(ID, getElementType(), getSizeModifier(),
1370            getIndexTypeCVRQualifiers());
1371  }
1372
1373  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1374                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1375    ID.AddPointer(ET.getAsOpaquePtr());
1376    ID.AddInteger(SizeMod);
1377    ID.AddInteger(TypeQuals);
1378  }
1379};
1380
1381/// VariableArrayType - This class represents C arrays with a specified size
1382/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1383/// Since the size expression is an arbitrary expression, we store it as such.
1384///
1385/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1386/// should not be: two lexically equivalent variable array types could mean
1387/// different things, for example, these variables do not have the same type
1388/// dynamically:
1389///
1390/// void foo(int x) {
1391///   int Y[x];
1392///   ++x;
1393///   int Z[x];
1394/// }
1395///
1396class VariableArrayType : public ArrayType {
1397  /// SizeExpr - An assignment expression. VLA's are only permitted within
1398  /// a function block.
1399  Stmt *SizeExpr;
1400  /// Brackets - The left and right array brackets.
1401  SourceRange Brackets;
1402
1403  VariableArrayType(QualType et, QualType can, Expr *e,
1404                    ArraySizeModifier sm, unsigned tq,
1405                    SourceRange brackets)
1406    : ArrayType(VariableArray, et, can, sm, tq),
1407      SizeExpr((Stmt*) e), Brackets(brackets) {}
1408  friend class ASTContext;  // ASTContext creates these.
1409  virtual void Destroy(ASTContext& C);
1410
1411public:
1412  Expr *getSizeExpr() const {
1413    // We use C-style casts instead of cast<> here because we do not wish
1414    // to have a dependency of Type.h on Stmt.h/Expr.h.
1415    return (Expr*) SizeExpr;
1416  }
1417  SourceRange getBracketsRange() const { return Brackets; }
1418  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1419  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1420
1421  virtual void getAsStringInternal(std::string &InnerString,
1422                                   const PrintingPolicy &Policy) const;
1423
1424  bool isSugared() const { return false; }
1425  QualType desugar() const { return QualType(this, 0); }
1426
1427  static bool classof(const Type *T) {
1428    return T->getTypeClass() == VariableArray;
1429  }
1430  static bool classof(const VariableArrayType *) { return true; }
1431
1432  friend class StmtIteratorBase;
1433
1434  void Profile(llvm::FoldingSetNodeID &ID) {
1435    assert(0 && "Cannnot unique VariableArrayTypes.");
1436  }
1437};
1438
1439/// DependentSizedArrayType - This type represents an array type in
1440/// C++ whose size is a value-dependent expression. For example:
1441/// @code
1442/// template<typename T, int Size>
1443/// class array {
1444///   T data[Size];
1445/// };
1446/// @endcode
1447/// For these types, we won't actually know what the array bound is
1448/// until template instantiation occurs, at which point this will
1449/// become either a ConstantArrayType or a VariableArrayType.
1450class DependentSizedArrayType : public ArrayType {
1451  ASTContext &Context;
1452
1453  /// SizeExpr - An assignment expression that will instantiate to the
1454  /// size of the array.
1455  Stmt *SizeExpr;
1456  /// Brackets - The left and right array brackets.
1457  SourceRange Brackets;
1458
1459  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1460                          Expr *e, ArraySizeModifier sm, unsigned tq,
1461                          SourceRange brackets)
1462    : ArrayType(DependentSizedArray, et, can, sm, tq),
1463      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1464  friend class ASTContext;  // ASTContext creates these.
1465  virtual void Destroy(ASTContext& C);
1466
1467public:
1468  Expr *getSizeExpr() const {
1469    // We use C-style casts instead of cast<> here because we do not wish
1470    // to have a dependency of Type.h on Stmt.h/Expr.h.
1471    return (Expr*) SizeExpr;
1472  }
1473  SourceRange getBracketsRange() const { return Brackets; }
1474  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1475  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1476
1477  virtual void getAsStringInternal(std::string &InnerString,
1478                                   const PrintingPolicy &Policy) const;
1479
1480  bool isSugared() const { return false; }
1481  QualType desugar() const { return QualType(this, 0); }
1482
1483  static bool classof(const Type *T) {
1484    return T->getTypeClass() == DependentSizedArray;
1485  }
1486  static bool classof(const DependentSizedArrayType *) { return true; }
1487
1488  friend class StmtIteratorBase;
1489
1490
1491  void Profile(llvm::FoldingSetNodeID &ID) {
1492    Profile(ID, Context, getElementType(),
1493            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1494  }
1495
1496  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1497                      QualType ET, ArraySizeModifier SizeMod,
1498                      unsigned TypeQuals, Expr *E);
1499};
1500
1501/// DependentSizedExtVectorType - This type represent an extended vector type
1502/// where either the type or size is dependent. For example:
1503/// @code
1504/// template<typename T, int Size>
1505/// class vector {
1506///   typedef T __attribute__((ext_vector_type(Size))) type;
1507/// }
1508/// @endcode
1509class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1510  ASTContext &Context;
1511  Expr *SizeExpr;
1512  /// ElementType - The element type of the array.
1513  QualType ElementType;
1514  SourceLocation loc;
1515
1516  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1517                              QualType can, Expr *SizeExpr, SourceLocation loc)
1518    : Type (DependentSizedExtVector, can, true),
1519      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1520      loc(loc) {}
1521  friend class ASTContext;
1522  virtual void Destroy(ASTContext& C);
1523
1524public:
1525  Expr *getSizeExpr() const { return SizeExpr; }
1526  QualType getElementType() const { return ElementType; }
1527  SourceLocation getAttributeLoc() const { return loc; }
1528
1529  virtual void getAsStringInternal(std::string &InnerString,
1530                                   const PrintingPolicy &Policy) const;
1531
1532  bool isSugared() const { return false; }
1533  QualType desugar() const { return QualType(this, 0); }
1534
1535  static bool classof(const Type *T) {
1536    return T->getTypeClass() == DependentSizedExtVector;
1537  }
1538  static bool classof(const DependentSizedExtVectorType *) { return true; }
1539
1540  void Profile(llvm::FoldingSetNodeID &ID) {
1541    Profile(ID, Context, getElementType(), getSizeExpr());
1542  }
1543
1544  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1545                      QualType ElementType, Expr *SizeExpr);
1546};
1547
1548
1549/// VectorType - GCC generic vector type. This type is created using
1550/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1551/// bytes. Since the constructor takes the number of vector elements, the
1552/// client is responsible for converting the size into the number of elements.
1553class VectorType : public Type, public llvm::FoldingSetNode {
1554protected:
1555  /// ElementType - The element type of the vector.
1556  QualType ElementType;
1557
1558  /// NumElements - The number of elements in the vector.
1559  unsigned NumElements;
1560
1561  VectorType(QualType vecType, unsigned nElements, QualType canonType) :
1562    Type(Vector, canonType, vecType->isDependentType()),
1563    ElementType(vecType), NumElements(nElements) {}
1564  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1565             QualType canonType)
1566    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1567      NumElements(nElements) {}
1568  friend class ASTContext;  // ASTContext creates these.
1569public:
1570
1571  QualType getElementType() const { return ElementType; }
1572  unsigned getNumElements() const { return NumElements; }
1573
1574  virtual void getAsStringInternal(std::string &InnerString,
1575                                   const PrintingPolicy &Policy) const;
1576
1577  bool isSugared() const { return false; }
1578  QualType desugar() const { return QualType(this, 0); }
1579
1580  void Profile(llvm::FoldingSetNodeID &ID) {
1581    Profile(ID, getElementType(), getNumElements(), getTypeClass());
1582  }
1583  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1584                      unsigned NumElements, TypeClass TypeClass) {
1585    ID.AddPointer(ElementType.getAsOpaquePtr());
1586    ID.AddInteger(NumElements);
1587    ID.AddInteger(TypeClass);
1588  }
1589  static bool classof(const Type *T) {
1590    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1591  }
1592  static bool classof(const VectorType *) { return true; }
1593};
1594
1595/// ExtVectorType - Extended vector type. This type is created using
1596/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1597/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1598/// class enables syntactic extensions, like Vector Components for accessing
1599/// points, colors, and textures (modeled after OpenGL Shading Language).
1600class ExtVectorType : public VectorType {
1601  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1602    VectorType(ExtVector, vecType, nElements, canonType) {}
1603  friend class ASTContext;  // ASTContext creates these.
1604public:
1605  static int getPointAccessorIdx(char c) {
1606    switch (c) {
1607    default: return -1;
1608    case 'x': return 0;
1609    case 'y': return 1;
1610    case 'z': return 2;
1611    case 'w': return 3;
1612    }
1613  }
1614  static int getNumericAccessorIdx(char c) {
1615    switch (c) {
1616      default: return -1;
1617      case '0': return 0;
1618      case '1': return 1;
1619      case '2': return 2;
1620      case '3': return 3;
1621      case '4': return 4;
1622      case '5': return 5;
1623      case '6': return 6;
1624      case '7': return 7;
1625      case '8': return 8;
1626      case '9': return 9;
1627      case 'A':
1628      case 'a': return 10;
1629      case 'B':
1630      case 'b': return 11;
1631      case 'C':
1632      case 'c': return 12;
1633      case 'D':
1634      case 'd': return 13;
1635      case 'E':
1636      case 'e': return 14;
1637      case 'F':
1638      case 'f': return 15;
1639    }
1640  }
1641
1642  static int getAccessorIdx(char c) {
1643    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1644    return getNumericAccessorIdx(c);
1645  }
1646
1647  bool isAccessorWithinNumElements(char c) const {
1648    if (int idx = getAccessorIdx(c)+1)
1649      return unsigned(idx-1) < NumElements;
1650    return false;
1651  }
1652  virtual void getAsStringInternal(std::string &InnerString,
1653                                   const PrintingPolicy &Policy) const;
1654
1655  bool isSugared() const { return false; }
1656  QualType desugar() const { return QualType(this, 0); }
1657
1658  static bool classof(const Type *T) {
1659    return T->getTypeClass() == ExtVector;
1660  }
1661  static bool classof(const ExtVectorType *) { return true; }
1662};
1663
1664/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1665/// class of FunctionNoProtoType and FunctionProtoType.
1666///
1667class FunctionType : public Type {
1668  /// SubClassData - This field is owned by the subclass, put here to pack
1669  /// tightly with the ivars in Type.
1670  bool SubClassData : 1;
1671
1672  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1673  /// other bitfields.
1674  /// The qualifiers are part of FunctionProtoType because...
1675  ///
1676  /// C++ 8.3.5p4: The return type, the parameter type list and the
1677  /// cv-qualifier-seq, [...], are part of the function type.
1678  ///
1679  unsigned TypeQuals : 3;
1680
1681  /// NoReturn - Indicates if the function type is attribute noreturn.
1682  unsigned NoReturn : 1;
1683
1684  // The type returned by the function.
1685  QualType ResultType;
1686protected:
1687  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1688               unsigned typeQuals, QualType Canonical, bool Dependent,
1689               bool noReturn = false)
1690    : Type(tc, Canonical, Dependent),
1691      SubClassData(SubclassInfo), TypeQuals(typeQuals), NoReturn(noReturn),
1692      ResultType(res) {}
1693  bool getSubClassData() const { return SubClassData; }
1694  unsigned getTypeQuals() const { return TypeQuals; }
1695public:
1696
1697  QualType getResultType() const { return ResultType; }
1698  bool getNoReturnAttr() const { return NoReturn; }
1699
1700  static bool classof(const Type *T) {
1701    return T->getTypeClass() == FunctionNoProto ||
1702           T->getTypeClass() == FunctionProto;
1703  }
1704  static bool classof(const FunctionType *) { return true; }
1705};
1706
1707/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1708/// no information available about its arguments.
1709class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1710  FunctionNoProtoType(QualType Result, QualType Canonical,
1711                      bool NoReturn = false)
1712    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1713                   /*Dependent=*/false, NoReturn) {}
1714  friend class ASTContext;  // ASTContext creates these.
1715public:
1716  // No additional state past what FunctionType provides.
1717
1718  virtual void getAsStringInternal(std::string &InnerString,
1719                                   const PrintingPolicy &Policy) const;
1720
1721  bool isSugared() const { return false; }
1722  QualType desugar() const { return QualType(this, 0); }
1723
1724  void Profile(llvm::FoldingSetNodeID &ID) {
1725    Profile(ID, getResultType(), getNoReturnAttr());
1726  }
1727  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1728                      bool NoReturn) {
1729    ID.AddInteger(NoReturn);
1730    ID.AddPointer(ResultType.getAsOpaquePtr());
1731  }
1732
1733  static bool classof(const Type *T) {
1734    return T->getTypeClass() == FunctionNoProto;
1735  }
1736  static bool classof(const FunctionNoProtoType *) { return true; }
1737};
1738
1739/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1740/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1741/// arguments, not as having a single void argument. Such a type can have an
1742/// exception specification, but this specification is not part of the canonical
1743/// type.
1744class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1745  /// hasAnyDependentType - Determine whether there are any dependent
1746  /// types within the arguments passed in.
1747  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1748    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1749      if (ArgArray[Idx]->isDependentType())
1750    return true;
1751
1752    return false;
1753  }
1754
1755  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1756                    bool isVariadic, unsigned typeQuals, bool hasExs,
1757                    bool hasAnyExs, const QualType *ExArray,
1758                    unsigned numExs, QualType Canonical, bool NoReturn)
1759    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1760                   (Result->isDependentType() ||
1761                    hasAnyDependentType(ArgArray, numArgs)), NoReturn),
1762      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1763      AnyExceptionSpec(hasAnyExs) {
1764    // Fill in the trailing argument array.
1765    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1766    for (unsigned i = 0; i != numArgs; ++i)
1767      ArgInfo[i] = ArgArray[i];
1768    // Fill in the exception array.
1769    QualType *Ex = ArgInfo + numArgs;
1770    for (unsigned i = 0; i != numExs; ++i)
1771      Ex[i] = ExArray[i];
1772  }
1773
1774  /// NumArgs - The number of arguments this function has, not counting '...'.
1775  unsigned NumArgs : 20;
1776
1777  /// NumExceptions - The number of types in the exception spec, if any.
1778  unsigned NumExceptions : 10;
1779
1780  /// HasExceptionSpec - Whether this function has an exception spec at all.
1781  bool HasExceptionSpec : 1;
1782
1783  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1784  bool AnyExceptionSpec : 1;
1785
1786  /// ArgInfo - There is an variable size array after the class in memory that
1787  /// holds the argument types.
1788
1789  /// Exceptions - There is another variable size array after ArgInfo that
1790  /// holds the exception types.
1791
1792  friend class ASTContext;  // ASTContext creates these.
1793
1794public:
1795  unsigned getNumArgs() const { return NumArgs; }
1796  QualType getArgType(unsigned i) const {
1797    assert(i < NumArgs && "Invalid argument number!");
1798    return arg_type_begin()[i];
1799  }
1800
1801  bool hasExceptionSpec() const { return HasExceptionSpec; }
1802  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1803  unsigned getNumExceptions() const { return NumExceptions; }
1804  QualType getExceptionType(unsigned i) const {
1805    assert(i < NumExceptions && "Invalid exception number!");
1806    return exception_begin()[i];
1807  }
1808  bool hasEmptyExceptionSpec() const {
1809    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1810      getNumExceptions() == 0;
1811  }
1812
1813  bool isVariadic() const { return getSubClassData(); }
1814  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1815
1816  typedef const QualType *arg_type_iterator;
1817  arg_type_iterator arg_type_begin() const {
1818    return reinterpret_cast<const QualType *>(this+1);
1819  }
1820  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1821
1822  typedef const QualType *exception_iterator;
1823  exception_iterator exception_begin() const {
1824    // exceptions begin where arguments end
1825    return arg_type_end();
1826  }
1827  exception_iterator exception_end() const {
1828    return exception_begin() + NumExceptions;
1829  }
1830
1831  virtual void getAsStringInternal(std::string &InnerString,
1832                                   const PrintingPolicy &Policy) const;
1833
1834  bool isSugared() const { return false; }
1835  QualType desugar() const { return QualType(this, 0); }
1836
1837  static bool classof(const Type *T) {
1838    return T->getTypeClass() == FunctionProto;
1839  }
1840  static bool classof(const FunctionProtoType *) { return true; }
1841
1842  void Profile(llvm::FoldingSetNodeID &ID);
1843  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1844                      arg_type_iterator ArgTys, unsigned NumArgs,
1845                      bool isVariadic, unsigned TypeQuals,
1846                      bool hasExceptionSpec, bool anyExceptionSpec,
1847                      unsigned NumExceptions, exception_iterator Exs,
1848                      bool NoReturn);
1849};
1850
1851
1852class TypedefType : public Type {
1853  TypedefDecl *Decl;
1854protected:
1855  TypedefType(TypeClass tc, TypedefDecl *D, QualType can)
1856    : Type(tc, can, can->isDependentType()), Decl(D) {
1857    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1858  }
1859  friend class ASTContext;  // ASTContext creates these.
1860public:
1861
1862  TypedefDecl *getDecl() const { return Decl; }
1863
1864  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1865  /// potentially looking through *all* consecutive typedefs.  This returns the
1866  /// sum of the type qualifiers, so if you have:
1867  ///   typedef const int A;
1868  ///   typedef volatile A B;
1869  /// looking through the typedefs for B will give you "const volatile A".
1870  QualType LookThroughTypedefs() const;
1871
1872  bool isSugared() const { return true; }
1873  QualType desugar() const;
1874
1875  virtual void getAsStringInternal(std::string &InnerString,
1876                                   const PrintingPolicy &Policy) const;
1877
1878  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
1879  static bool classof(const TypedefType *) { return true; }
1880};
1881
1882/// TypeOfExprType (GCC extension).
1883class TypeOfExprType : public Type {
1884  Expr *TOExpr;
1885
1886protected:
1887  TypeOfExprType(Expr *E, QualType can = QualType());
1888  friend class ASTContext;  // ASTContext creates these.
1889public:
1890  Expr *getUnderlyingExpr() const { return TOExpr; }
1891
1892  /// \brief Remove a single level of sugar.
1893  QualType desugar() const;
1894
1895  /// \brief Returns whether this type directly provides sugar.
1896  bool isSugared() const { return true; }
1897
1898  virtual void getAsStringInternal(std::string &InnerString,
1899                                   const PrintingPolicy &Policy) const;
1900
1901  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
1902  static bool classof(const TypeOfExprType *) { return true; }
1903};
1904
1905/// Subclass of TypeOfExprType that is used for canonical, dependent
1906/// typeof(expr) types.
1907class DependentTypeOfExprType
1908  : public TypeOfExprType, public llvm::FoldingSetNode {
1909  ASTContext &Context;
1910
1911public:
1912  DependentTypeOfExprType(ASTContext &Context, Expr *E)
1913    : TypeOfExprType(E), Context(Context) { }
1914
1915  bool isSugared() const { return false; }
1916  QualType desugar() const { return QualType(this, 0); }
1917
1918  void Profile(llvm::FoldingSetNodeID &ID) {
1919    Profile(ID, Context, getUnderlyingExpr());
1920  }
1921
1922  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1923                      Expr *E);
1924};
1925
1926/// TypeOfType (GCC extension).
1927class TypeOfType : public Type {
1928  QualType TOType;
1929  TypeOfType(QualType T, QualType can)
1930    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
1931    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1932  }
1933  friend class ASTContext;  // ASTContext creates these.
1934public:
1935  QualType getUnderlyingType() const { return TOType; }
1936
1937  /// \brief Remove a single level of sugar.
1938  QualType desugar() const { return getUnderlyingType(); }
1939
1940  /// \brief Returns whether this type directly provides sugar.
1941  bool isSugared() const { return true; }
1942
1943  virtual void getAsStringInternal(std::string &InnerString,
1944                                   const PrintingPolicy &Policy) const;
1945
1946  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
1947  static bool classof(const TypeOfType *) { return true; }
1948};
1949
1950/// DecltypeType (C++0x)
1951class DecltypeType : public Type {
1952  Expr *E;
1953
1954  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
1955  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
1956  // from it.
1957  QualType UnderlyingType;
1958
1959protected:
1960  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
1961  friend class ASTContext;  // ASTContext creates these.
1962public:
1963  Expr *getUnderlyingExpr() const { return E; }
1964  QualType getUnderlyingType() const { return UnderlyingType; }
1965
1966  /// \brief Remove a single level of sugar.
1967  QualType desugar() const { return getUnderlyingType(); }
1968
1969  /// \brief Returns whether this type directly provides sugar.
1970  bool isSugared() const { return !isDependentType(); }
1971
1972  virtual void getAsStringInternal(std::string &InnerString,
1973                                   const PrintingPolicy &Policy) const;
1974
1975  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
1976  static bool classof(const DecltypeType *) { return true; }
1977};
1978
1979/// Subclass of DecltypeType that is used for canonical, dependent
1980/// C++0x decltype types.
1981class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
1982  ASTContext &Context;
1983
1984public:
1985  DependentDecltypeType(ASTContext &Context, Expr *E);
1986
1987  bool isSugared() const { return false; }
1988  QualType desugar() const { return QualType(this, 0); }
1989
1990  void Profile(llvm::FoldingSetNodeID &ID) {
1991    Profile(ID, Context, getUnderlyingExpr());
1992  }
1993
1994  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1995                      Expr *E);
1996};
1997
1998class TagType : public Type {
1999  /// Stores the TagDecl associated with this type. The decl will
2000  /// point to the TagDecl that actually defines the entity (or is a
2001  /// definition in progress), if there is such a definition. The
2002  /// single-bit value will be non-zero when this tag is in the
2003  /// process of being defined.
2004  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
2005  friend class ASTContext;
2006  friend class TagDecl;
2007
2008protected:
2009  TagType(TypeClass TC, TagDecl *D, QualType can);
2010
2011public:
2012  TagDecl *getDecl() const { return decl.getPointer(); }
2013
2014  /// @brief Determines whether this type is in the process of being
2015  /// defined.
2016  bool isBeingDefined() const { return decl.getInt(); }
2017  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
2018
2019  virtual void getAsStringInternal(std::string &InnerString,
2020                                   const PrintingPolicy &Policy) const;
2021
2022  static bool classof(const Type *T) {
2023    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2024  }
2025  static bool classof(const TagType *) { return true; }
2026  static bool classof(const RecordType *) { return true; }
2027  static bool classof(const EnumType *) { return true; }
2028};
2029
2030/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2031/// to detect TagType objects of structs/unions/classes.
2032class RecordType : public TagType {
2033protected:
2034  explicit RecordType(RecordDecl *D)
2035    : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { }
2036  explicit RecordType(TypeClass TC, RecordDecl *D)
2037    : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { }
2038  friend class ASTContext;   // ASTContext creates these.
2039public:
2040
2041  RecordDecl *getDecl() const {
2042    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2043  }
2044
2045  // FIXME: This predicate is a helper to QualType/Type. It needs to
2046  // recursively check all fields for const-ness. If any field is declared
2047  // const, it needs to return false.
2048  bool hasConstFields() const { return false; }
2049
2050  // FIXME: RecordType needs to check when it is created that all fields are in
2051  // the same address space, and return that.
2052  unsigned getAddressSpace() const { return 0; }
2053
2054  bool isSugared() const { return false; }
2055  QualType desugar() const { return QualType(this, 0); }
2056
2057  static bool classof(const TagType *T);
2058  static bool classof(const Type *T) {
2059    return isa<TagType>(T) && classof(cast<TagType>(T));
2060  }
2061  static bool classof(const RecordType *) { return true; }
2062};
2063
2064/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2065/// to detect TagType objects of enums.
2066class EnumType : public TagType {
2067  explicit EnumType(EnumDecl *D)
2068    : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { }
2069  friend class ASTContext;   // ASTContext creates these.
2070public:
2071
2072  EnumDecl *getDecl() const {
2073    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2074  }
2075
2076  bool isSugared() const { return false; }
2077  QualType desugar() const { return QualType(this, 0); }
2078
2079  static bool classof(const TagType *T);
2080  static bool classof(const Type *T) {
2081    return isa<TagType>(T) && classof(cast<TagType>(T));
2082  }
2083  static bool classof(const EnumType *) { return true; }
2084};
2085
2086/// ElaboratedType - A non-canonical type used to represents uses of
2087/// elaborated type specifiers in C++.  For example:
2088///
2089///   void foo(union MyUnion);
2090///            ^^^^^^^^^^^^^
2091///
2092/// At the moment, for efficiency we do not create elaborated types in
2093/// C, since outside of typedefs all references to structs would
2094/// necessarily be elaborated.
2095class ElaboratedType : public Type, public llvm::FoldingSetNode {
2096public:
2097  enum TagKind {
2098    TK_struct,
2099    TK_union,
2100    TK_class,
2101    TK_enum
2102  };
2103
2104private:
2105  /// The tag that was used in this elaborated type specifier.
2106  TagKind Tag;
2107
2108  /// The underlying type.
2109  QualType UnderlyingType;
2110
2111  explicit ElaboratedType(QualType Ty, TagKind Tag, QualType Canon)
2112    : Type(Elaborated, Canon, Canon->isDependentType()),
2113      Tag(Tag), UnderlyingType(Ty) { }
2114  friend class ASTContext;   // ASTContext creates these.
2115
2116public:
2117  TagKind getTagKind() const { return Tag; }
2118  QualType getUnderlyingType() const { return UnderlyingType; }
2119
2120  /// \brief Remove a single level of sugar.
2121  QualType desugar() const { return getUnderlyingType(); }
2122
2123  /// \brief Returns whether this type directly provides sugar.
2124  bool isSugared() const { return true; }
2125
2126  static const char *getNameForTagKind(TagKind Kind) {
2127    switch (Kind) {
2128    default: assert(0 && "Unknown TagKind!");
2129    case TK_struct: return "struct";
2130    case TK_union:  return "union";
2131    case TK_class:  return "class";
2132    case TK_enum:   return "enum";
2133    }
2134  }
2135
2136  virtual void getAsStringInternal(std::string &InnerString,
2137                                   const PrintingPolicy &Policy) const;
2138
2139  void Profile(llvm::FoldingSetNodeID &ID) {
2140    Profile(ID, getUnderlyingType(), getTagKind());
2141  }
2142  static void Profile(llvm::FoldingSetNodeID &ID, QualType T, TagKind Tag) {
2143    ID.AddPointer(T.getAsOpaquePtr());
2144    ID.AddInteger(Tag);
2145  }
2146
2147  static bool classof(const ElaboratedType*) { return true; }
2148  static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
2149};
2150
2151class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2152  unsigned Depth : 15;
2153  unsigned Index : 16;
2154  unsigned ParameterPack : 1;
2155  IdentifierInfo *Name;
2156
2157  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2158                       QualType Canon)
2159    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2160      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2161
2162  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2163    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2164      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2165
2166  friend class ASTContext;  // ASTContext creates these
2167
2168public:
2169  unsigned getDepth() const { return Depth; }
2170  unsigned getIndex() const { return Index; }
2171  bool isParameterPack() const { return ParameterPack; }
2172  IdentifierInfo *getName() const { return Name; }
2173
2174  virtual void getAsStringInternal(std::string &InnerString,
2175                                   const PrintingPolicy &Policy) const;
2176
2177  bool isSugared() const { return false; }
2178  QualType desugar() const { return QualType(this, 0); }
2179
2180  void Profile(llvm::FoldingSetNodeID &ID) {
2181    Profile(ID, Depth, Index, ParameterPack, Name);
2182  }
2183
2184  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2185                      unsigned Index, bool ParameterPack,
2186                      IdentifierInfo *Name) {
2187    ID.AddInteger(Depth);
2188    ID.AddInteger(Index);
2189    ID.AddBoolean(ParameterPack);
2190    ID.AddPointer(Name);
2191  }
2192
2193  static bool classof(const Type *T) {
2194    return T->getTypeClass() == TemplateTypeParm;
2195  }
2196  static bool classof(const TemplateTypeParmType *T) { return true; }
2197};
2198
2199/// \brief Represents the result of substituting a type for a template
2200/// type parameter.
2201///
2202/// Within an instantiated template, all template type parameters have
2203/// been replaced with these.  They are used solely to record that a
2204/// type was originally written as a template type parameter;
2205/// therefore they are never canonical.
2206class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2207  // The original type parameter.
2208  const TemplateTypeParmType *Replaced;
2209
2210  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2211    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType()),
2212      Replaced(Param) { }
2213
2214  friend class ASTContext;
2215
2216public:
2217  IdentifierInfo *getName() const { return Replaced->getName(); }
2218
2219  /// Gets the template parameter that was substituted for.
2220  const TemplateTypeParmType *getReplacedParameter() const {
2221    return Replaced;
2222  }
2223
2224  /// Gets the type that was substituted for the template
2225  /// parameter.
2226  QualType getReplacementType() const {
2227    return getCanonicalTypeInternal();
2228  }
2229
2230  virtual void getAsStringInternal(std::string &InnerString,
2231                                   const PrintingPolicy &Policy) const;
2232
2233  bool isSugared() const { return true; }
2234  QualType desugar() const { return getReplacementType(); }
2235
2236  void Profile(llvm::FoldingSetNodeID &ID) {
2237    Profile(ID, getReplacedParameter(), getReplacementType());
2238  }
2239  static void Profile(llvm::FoldingSetNodeID &ID,
2240                      const TemplateTypeParmType *Replaced,
2241                      QualType Replacement) {
2242    ID.AddPointer(Replaced);
2243    ID.AddPointer(Replacement.getAsOpaquePtr());
2244  }
2245
2246  static bool classof(const Type *T) {
2247    return T->getTypeClass() == SubstTemplateTypeParm;
2248  }
2249  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2250};
2251
2252/// \brief Represents the type of a template specialization as written
2253/// in the source code.
2254///
2255/// Template specialization types represent the syntactic form of a
2256/// template-id that refers to a type, e.g., @c vector<int>. Some
2257/// template specialization types are syntactic sugar, whose canonical
2258/// type will point to some other type node that represents the
2259/// instantiation or class template specialization. For example, a
2260/// class template specialization type of @c vector<int> will refer to
2261/// a tag type for the instantiation
2262/// @c std::vector<int, std::allocator<int>>.
2263///
2264/// Other template specialization types, for which the template name
2265/// is dependent, may be canonical types. These types are always
2266/// dependent.
2267class TemplateSpecializationType
2268  : public Type, public llvm::FoldingSetNode {
2269
2270  // FIXME: Currently needed for profiling expressions; can we avoid this?
2271  ASTContext &Context;
2272
2273    /// \brief The name of the template being specialized.
2274  TemplateName Template;
2275
2276  /// \brief - The number of template arguments named in this class
2277  /// template specialization.
2278  unsigned NumArgs;
2279
2280  TemplateSpecializationType(ASTContext &Context,
2281                             TemplateName T,
2282                             const TemplateArgument *Args,
2283                             unsigned NumArgs, QualType Canon);
2284
2285  virtual void Destroy(ASTContext& C);
2286
2287  friend class ASTContext;  // ASTContext creates these
2288
2289public:
2290  /// \brief Determine whether any of the given template arguments are
2291  /// dependent.
2292  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2293                                            unsigned NumArgs);
2294
2295  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2296                                            unsigned NumArgs);
2297
2298  /// \brief Print a template argument list, including the '<' and '>'
2299  /// enclosing the template arguments.
2300  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2301                                               unsigned NumArgs,
2302                                               const PrintingPolicy &Policy);
2303
2304  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2305                                               unsigned NumArgs,
2306                                               const PrintingPolicy &Policy);
2307
2308  typedef const TemplateArgument * iterator;
2309
2310  iterator begin() const { return getArgs(); }
2311  iterator end() const;
2312
2313  /// \brief Retrieve the name of the template that we are specializing.
2314  TemplateName getTemplateName() const { return Template; }
2315
2316  /// \brief Retrieve the template arguments.
2317  const TemplateArgument *getArgs() const {
2318    return reinterpret_cast<const TemplateArgument *>(this + 1);
2319  }
2320
2321  /// \brief Retrieve the number of template arguments.
2322  unsigned getNumArgs() const { return NumArgs; }
2323
2324  /// \brief Retrieve a specific template argument as a type.
2325  /// \precondition @c isArgType(Arg)
2326  const TemplateArgument &getArg(unsigned Idx) const;
2327
2328  virtual void getAsStringInternal(std::string &InnerString,
2329                                   const PrintingPolicy &Policy) const;
2330
2331  bool isSugared() const { return !isDependentType(); }
2332  QualType desugar() const { return getCanonicalTypeInternal(); }
2333
2334  void Profile(llvm::FoldingSetNodeID &ID) {
2335    Profile(ID, Template, getArgs(), NumArgs, Context);
2336  }
2337
2338  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2339                      const TemplateArgument *Args, unsigned NumArgs,
2340                      ASTContext &Context);
2341
2342  static bool classof(const Type *T) {
2343    return T->getTypeClass() == TemplateSpecialization;
2344  }
2345  static bool classof(const TemplateSpecializationType *T) { return true; }
2346};
2347
2348/// \brief Represents a type that was referred to via a qualified
2349/// name, e.g., N::M::type.
2350///
2351/// This type is used to keep track of a type name as written in the
2352/// source code, including any nested-name-specifiers. The type itself
2353/// is always "sugar", used to express what was written in the source
2354/// code but containing no additional semantic information.
2355class QualifiedNameType : public Type, public llvm::FoldingSetNode {
2356  /// \brief The nested name specifier containing the qualifier.
2357  NestedNameSpecifier *NNS;
2358
2359  /// \brief The type that this qualified name refers to.
2360  QualType NamedType;
2361
2362  QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType,
2363                    QualType CanonType)
2364    : Type(QualifiedName, CanonType, NamedType->isDependentType()),
2365      NNS(NNS), NamedType(NamedType) { }
2366
2367  friend class ASTContext;  // ASTContext creates these
2368
2369public:
2370  /// \brief Retrieve the qualification on this type.
2371  NestedNameSpecifier *getQualifier() const { return NNS; }
2372
2373  /// \brief Retrieve the type named by the qualified-id.
2374  QualType getNamedType() const { return NamedType; }
2375
2376  /// \brief Remove a single level of sugar.
2377  QualType desugar() const { return getNamedType(); }
2378
2379  /// \brief Returns whether this type directly provides sugar.
2380  bool isSugared() const { return true; }
2381
2382  virtual void getAsStringInternal(std::string &InnerString,
2383                                   const PrintingPolicy &Policy) const;
2384
2385  void Profile(llvm::FoldingSetNodeID &ID) {
2386    Profile(ID, NNS, NamedType);
2387  }
2388
2389  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2390                      QualType NamedType) {
2391    ID.AddPointer(NNS);
2392    NamedType.Profile(ID);
2393  }
2394
2395  static bool classof(const Type *T) {
2396    return T->getTypeClass() == QualifiedName;
2397  }
2398  static bool classof(const QualifiedNameType *T) { return true; }
2399};
2400
2401/// \brief Represents a 'typename' specifier that names a type within
2402/// a dependent type, e.g., "typename T::type".
2403///
2404/// TypenameType has a very similar structure to QualifiedNameType,
2405/// which also involves a nested-name-specifier following by a type,
2406/// and (FIXME!) both can even be prefixed by the 'typename'
2407/// keyword. However, the two types serve very different roles:
2408/// QualifiedNameType is a non-semantic type that serves only as sugar
2409/// to show how a particular type was written in the source
2410/// code. TypenameType, on the other hand, only occurs when the
2411/// nested-name-specifier is dependent, such that we cannot resolve
2412/// the actual type until after instantiation.
2413class TypenameType : public Type, public llvm::FoldingSetNode {
2414  /// \brief The nested name specifier containing the qualifier.
2415  NestedNameSpecifier *NNS;
2416
2417  typedef llvm::PointerUnion<const IdentifierInfo *,
2418                             const TemplateSpecializationType *> NameType;
2419
2420  /// \brief The type that this typename specifier refers to.
2421  NameType Name;
2422
2423  TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2424               QualType CanonType)
2425    : Type(Typename, CanonType, true), NNS(NNS), Name(Name) {
2426    assert(NNS->isDependent() &&
2427           "TypenameType requires a dependent nested-name-specifier");
2428  }
2429
2430  TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty,
2431               QualType CanonType)
2432    : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) {
2433    assert(NNS->isDependent() &&
2434           "TypenameType requires a dependent nested-name-specifier");
2435  }
2436
2437  friend class ASTContext;  // ASTContext creates these
2438
2439public:
2440  /// \brief Retrieve the qualification on this type.
2441  NestedNameSpecifier *getQualifier() const { return NNS; }
2442
2443  /// \brief Retrieve the type named by the typename specifier as an
2444  /// identifier.
2445  ///
2446  /// This routine will return a non-NULL identifier pointer when the
2447  /// form of the original typename was terminated by an identifier,
2448  /// e.g., "typename T::type".
2449  const IdentifierInfo *getIdentifier() const {
2450    return Name.dyn_cast<const IdentifierInfo *>();
2451  }
2452
2453  /// \brief Retrieve the type named by the typename specifier as a
2454  /// type specialization.
2455  const TemplateSpecializationType *getTemplateId() const {
2456    return Name.dyn_cast<const TemplateSpecializationType *>();
2457  }
2458
2459  virtual void getAsStringInternal(std::string &InnerString,
2460                                   const PrintingPolicy &Policy) const;
2461
2462  bool isSugared() const { return false; }
2463  QualType desugar() const { return QualType(this, 0); }
2464
2465  void Profile(llvm::FoldingSetNodeID &ID) {
2466    Profile(ID, NNS, Name);
2467  }
2468
2469  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2470                      NameType Name) {
2471    ID.AddPointer(NNS);
2472    ID.AddPointer(Name.getOpaqueValue());
2473  }
2474
2475  static bool classof(const Type *T) {
2476    return T->getTypeClass() == Typename;
2477  }
2478  static bool classof(const TypenameType *T) { return true; }
2479};
2480
2481/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2482/// object oriented design.  They basically correspond to C++ classes.  There
2483/// are two kinds of interface types, normal interfaces like "NSString" and
2484/// qualified interfaces, which are qualified with a protocol list like
2485/// "NSString<NSCopyable, NSAmazing>".
2486class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
2487  ObjCInterfaceDecl *Decl;
2488
2489  // List of protocols for this protocol conforming object type
2490  // List is sorted on protocol name. No protocol is enterred more than once.
2491  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
2492
2493  ObjCInterfaceType(QualType Canonical, ObjCInterfaceDecl *D,
2494                    ObjCProtocolDecl **Protos, unsigned NumP) :
2495    Type(ObjCInterface, Canonical, /*Dependent=*/false),
2496    Decl(D), Protocols(Protos, Protos+NumP) { }
2497  friend class ASTContext;  // ASTContext creates these.
2498public:
2499  ObjCInterfaceDecl *getDecl() const { return Decl; }
2500
2501  /// getNumProtocols - Return the number of qualifying protocols in this
2502  /// interface type, or 0 if there are none.
2503  unsigned getNumProtocols() const { return Protocols.size(); }
2504
2505  /// qual_iterator and friends: this provides access to the (potentially empty)
2506  /// list of protocols qualifying this interface.
2507  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2508  qual_iterator qual_begin() const { return Protocols.begin(); }
2509  qual_iterator qual_end() const   { return Protocols.end(); }
2510  bool qual_empty() const { return Protocols.size() == 0; }
2511
2512  virtual void getAsStringInternal(std::string &InnerString,
2513                                   const PrintingPolicy &Policy) const;
2514
2515  bool isSugared() const { return false; }
2516  QualType desugar() const { return QualType(this, 0); }
2517
2518  void Profile(llvm::FoldingSetNodeID &ID);
2519  static void Profile(llvm::FoldingSetNodeID &ID,
2520                      const ObjCInterfaceDecl *Decl,
2521                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2522
2523  static bool classof(const Type *T) {
2524    return T->getTypeClass() == ObjCInterface;
2525  }
2526  static bool classof(const ObjCInterfaceType *) { return true; }
2527};
2528
2529/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2530/// and 'Interface <p> *'.
2531///
2532/// Duplicate protocols are removed and protocol list is canonicalized to be in
2533/// alphabetical order.
2534class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2535  QualType PointeeType; // A builtin or interface type.
2536
2537  // List of protocols for this protocol conforming object type
2538  // List is sorted on protocol name. No protocol is entered more than once.
2539  llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols;
2540
2541  ObjCObjectPointerType(QualType Canonical, QualType T,
2542                        ObjCProtocolDecl **Protos, unsigned NumP) :
2543    Type(ObjCObjectPointer, Canonical, /*Dependent=*/false),
2544    PointeeType(T), Protocols(Protos, Protos+NumP) { }
2545  friend class ASTContext;  // ASTContext creates these.
2546
2547public:
2548  // Get the pointee type. Pointee will either be:
2549  // - a built-in type (for 'id' and 'Class').
2550  // - an interface type (for user-defined types).
2551  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2552  //   For example: typedef NSObject T; T *var;
2553  QualType getPointeeType() const { return PointeeType; }
2554
2555  const ObjCInterfaceType *getInterfaceType() const {
2556    return PointeeType->getAs<ObjCInterfaceType>();
2557  }
2558  /// getInterfaceDecl - returns an interface decl for user-defined types.
2559  ObjCInterfaceDecl *getInterfaceDecl() const {
2560    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2561  }
2562  /// isObjCIdType - true for "id".
2563  bool isObjCIdType() const {
2564    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2565           !Protocols.size();
2566  }
2567  /// isObjCClassType - true for "Class".
2568  bool isObjCClassType() const {
2569    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2570           !Protocols.size();
2571  }
2572  /// isObjCQualifiedIdType - true for "id <p>".
2573  bool isObjCQualifiedIdType() const {
2574    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2575           Protocols.size();
2576  }
2577  /// isObjCQualifiedClassType - true for "Class <p>".
2578  bool isObjCQualifiedClassType() const {
2579    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2580           Protocols.size();
2581  }
2582  /// qual_iterator and friends: this provides access to the (potentially empty)
2583  /// list of protocols qualifying this interface.
2584  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2585
2586  qual_iterator qual_begin() const { return Protocols.begin(); }
2587  qual_iterator qual_end() const   { return Protocols.end(); }
2588  bool qual_empty() const { return Protocols.size() == 0; }
2589
2590  /// getNumProtocols - Return the number of qualifying protocols in this
2591  /// interface type, or 0 if there are none.
2592  unsigned getNumProtocols() const { return Protocols.size(); }
2593
2594  bool isSugared() const { return false; }
2595  QualType desugar() const { return QualType(this, 0); }
2596
2597  void Profile(llvm::FoldingSetNodeID &ID);
2598  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2599                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2600  virtual void getAsStringInternal(std::string &InnerString,
2601                                   const PrintingPolicy &Policy) const;
2602  static bool classof(const Type *T) {
2603    return T->getTypeClass() == ObjCObjectPointer;
2604  }
2605  static bool classof(const ObjCObjectPointerType *) { return true; }
2606};
2607
2608/// A qualifier set is used to build a set of qualifiers.
2609class QualifierCollector : public Qualifiers {
2610  ASTContext *Context;
2611
2612public:
2613  QualifierCollector(Qualifiers Qs = Qualifiers())
2614    : Qualifiers(Qs), Context(0) {}
2615  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
2616    : Qualifiers(Qs), Context(&Context) {}
2617
2618  void setContext(ASTContext &C) { Context = &C; }
2619
2620  /// Collect any qualifiers on the given type and return an
2621  /// unqualified type.
2622  const Type *strip(QualType QT) {
2623    addFastQualifiers(QT.getFastQualifiers());
2624    if (QT.hasNonFastQualifiers()) {
2625      const ExtQuals *EQ = QT.getExtQualsUnsafe();
2626      Context = &EQ->getContext();
2627      addQualifiers(EQ->getQualifiers());
2628      return EQ->getBaseType();
2629    }
2630    return QT.getTypePtrUnsafe();
2631  }
2632
2633  /// Apply the collected qualifiers to the given type.
2634  QualType apply(QualType QT) const;
2635
2636  /// Apply the collected qualifiers to the given type.
2637  QualType apply(const Type* T) const;
2638
2639};
2640
2641
2642// Inline function definitions.
2643
2644inline bool QualType::isCanonical() const {
2645  const Type *T = getTypePtr();
2646  if (hasQualifiers())
2647    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
2648  return T->isCanonicalUnqualified();
2649}
2650
2651inline bool QualType::isCanonicalAsParam() const {
2652  if (hasQualifiers()) return false;
2653  const Type *T = getTypePtr();
2654  return T->isCanonicalUnqualified() &&
2655           !isa<FunctionType>(T) && !isa<ArrayType>(T);
2656}
2657
2658inline void QualType::removeConst() {
2659  removeFastQualifiers(Qualifiers::Const);
2660}
2661
2662inline void QualType::removeRestrict() {
2663  removeFastQualifiers(Qualifiers::Restrict);
2664}
2665
2666inline void QualType::removeVolatile() {
2667  QualifierCollector Qc;
2668  const Type *Ty = Qc.strip(*this);
2669  if (Qc.hasVolatile()) {
2670    Qc.removeVolatile();
2671    *this = Qc.apply(Ty);
2672  }
2673}
2674
2675inline void QualType::removeCVRQualifiers(unsigned Mask) {
2676  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
2677
2678  // Fast path: we don't need to touch the slow qualifiers.
2679  if (!(Mask & ~Qualifiers::FastMask)) {
2680    removeFastQualifiers(Mask);
2681    return;
2682  }
2683
2684  QualifierCollector Qc;
2685  const Type *Ty = Qc.strip(*this);
2686  Qc.removeCVRQualifiers(Mask);
2687  *this = Qc.apply(Ty);
2688}
2689
2690/// getAddressSpace - Return the address space of this type.
2691inline unsigned QualType::getAddressSpace() const {
2692  if (hasNonFastQualifiers()) {
2693    const ExtQuals *EQ = getExtQualsUnsafe();
2694    if (EQ->hasAddressSpace())
2695      return EQ->getAddressSpace();
2696  }
2697
2698  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2699  if (CT.hasNonFastQualifiers()) {
2700    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2701    if (EQ->hasAddressSpace())
2702      return EQ->getAddressSpace();
2703  }
2704
2705  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2706    return AT->getElementType().getAddressSpace();
2707  if (const RecordType *RT = dyn_cast<RecordType>(CT))
2708    return RT->getAddressSpace();
2709  return 0;
2710}
2711
2712/// getObjCGCAttr - Return the gc attribute of this type.
2713inline Qualifiers::GC QualType::getObjCGCAttr() const {
2714  if (hasNonFastQualifiers()) {
2715    const ExtQuals *EQ = getExtQualsUnsafe();
2716    if (EQ->hasObjCGCAttr())
2717      return EQ->getObjCGCAttr();
2718  }
2719
2720  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2721  if (CT.hasNonFastQualifiers()) {
2722    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2723    if (EQ->hasObjCGCAttr())
2724      return EQ->getObjCGCAttr();
2725  }
2726
2727  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2728      return AT->getElementType().getObjCGCAttr();
2729  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
2730    return PT->getPointeeType().getObjCGCAttr();
2731  // We most look at all pointer types, not just pointer to interface types.
2732  if (const PointerType *PT = CT->getAs<PointerType>())
2733    return PT->getPointeeType().getObjCGCAttr();
2734  return Qualifiers::GCNone;
2735}
2736
2737  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
2738  /// false otherwise.
2739inline bool QualType::getNoReturnAttr() const {
2740  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2741  if (const PointerType *PT = getTypePtr()->getAs<PointerType>()) {
2742    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
2743      return FT->getNoReturnAttr();
2744  } else if (const FunctionType *FT = getTypePtr()->getAs<FunctionType>())
2745    return FT->getNoReturnAttr();
2746
2747  return false;
2748}
2749
2750/// isMoreQualifiedThan - Determine whether this type is more
2751/// qualified than the Other type. For example, "const volatile int"
2752/// is more qualified than "const int", "volatile int", and
2753/// "int". However, it is not more qualified than "const volatile
2754/// int".
2755inline bool QualType::isMoreQualifiedThan(QualType Other) const {
2756  // FIXME: work on arbitrary qualifiers
2757  unsigned MyQuals = this->getCVRQualifiers();
2758  unsigned OtherQuals = Other.getCVRQualifiers();
2759  if (getAddressSpace() != Other.getAddressSpace())
2760    return false;
2761  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
2762}
2763
2764/// isAtLeastAsQualifiedAs - Determine whether this type is at last
2765/// as qualified as the Other type. For example, "const volatile
2766/// int" is at least as qualified as "const int", "volatile int",
2767/// "int", and "const volatile int".
2768inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
2769  // FIXME: work on arbitrary qualifiers
2770  unsigned MyQuals = this->getCVRQualifiers();
2771  unsigned OtherQuals = Other.getCVRQualifiers();
2772  if (getAddressSpace() != Other.getAddressSpace())
2773    return false;
2774  return (MyQuals | OtherQuals) == MyQuals;
2775}
2776
2777/// getNonReferenceType - If Type is a reference type (e.g., const
2778/// int&), returns the type that the reference refers to ("const
2779/// int"). Otherwise, returns the type itself. This routine is used
2780/// throughout Sema to implement C++ 5p6:
2781///
2782///   If an expression initially has the type "reference to T" (8.3.2,
2783///   8.5.3), the type is adjusted to "T" prior to any further
2784///   analysis, the expression designates the object or function
2785///   denoted by the reference, and the expression is an lvalue.
2786inline QualType QualType::getNonReferenceType() const {
2787  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
2788    return RefType->getPointeeType();
2789  else
2790    return *this;
2791}
2792
2793inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
2794  if (const PointerType *PT = getAs<PointerType>())
2795    return PT->getPointeeType()->getAs<ObjCInterfaceType>();
2796  return 0;
2797}
2798
2799// NOTE: All of these methods use "getUnqualifiedType" to strip off address
2800// space qualifiers if present.
2801inline bool Type::isFunctionType() const {
2802  return isa<FunctionType>(CanonicalType.getUnqualifiedType());
2803}
2804inline bool Type::isPointerType() const {
2805  return isa<PointerType>(CanonicalType.getUnqualifiedType());
2806}
2807inline bool Type::isAnyPointerType() const {
2808  return isPointerType() || isObjCObjectPointerType();
2809}
2810inline bool Type::isBlockPointerType() const {
2811  return isa<BlockPointerType>(CanonicalType.getUnqualifiedType());
2812}
2813inline bool Type::isReferenceType() const {
2814  return isa<ReferenceType>(CanonicalType.getUnqualifiedType());
2815}
2816inline bool Type::isLValueReferenceType() const {
2817  return isa<LValueReferenceType>(CanonicalType.getUnqualifiedType());
2818}
2819inline bool Type::isRValueReferenceType() const {
2820  return isa<RValueReferenceType>(CanonicalType.getUnqualifiedType());
2821}
2822inline bool Type::isFunctionPointerType() const {
2823  if (const PointerType* T = getAs<PointerType>())
2824    return T->getPointeeType()->isFunctionType();
2825  else
2826    return false;
2827}
2828inline bool Type::isMemberPointerType() const {
2829  return isa<MemberPointerType>(CanonicalType.getUnqualifiedType());
2830}
2831inline bool Type::isMemberFunctionPointerType() const {
2832  if (const MemberPointerType* T = getAs<MemberPointerType>())
2833    return T->getPointeeType()->isFunctionType();
2834  else
2835    return false;
2836}
2837inline bool Type::isArrayType() const {
2838  return isa<ArrayType>(CanonicalType.getUnqualifiedType());
2839}
2840inline bool Type::isConstantArrayType() const {
2841  return isa<ConstantArrayType>(CanonicalType.getUnqualifiedType());
2842}
2843inline bool Type::isIncompleteArrayType() const {
2844  return isa<IncompleteArrayType>(CanonicalType.getUnqualifiedType());
2845}
2846inline bool Type::isVariableArrayType() const {
2847  return isa<VariableArrayType>(CanonicalType.getUnqualifiedType());
2848}
2849inline bool Type::isDependentSizedArrayType() const {
2850  return isa<DependentSizedArrayType>(CanonicalType.getUnqualifiedType());
2851}
2852inline bool Type::isRecordType() const {
2853  return isa<RecordType>(CanonicalType.getUnqualifiedType());
2854}
2855inline bool Type::isAnyComplexType() const {
2856  return isa<ComplexType>(CanonicalType.getUnqualifiedType());
2857}
2858inline bool Type::isVectorType() const {
2859  return isa<VectorType>(CanonicalType.getUnqualifiedType());
2860}
2861inline bool Type::isExtVectorType() const {
2862  return isa<ExtVectorType>(CanonicalType.getUnqualifiedType());
2863}
2864inline bool Type::isObjCObjectPointerType() const {
2865  return isa<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
2866}
2867inline bool Type::isObjCInterfaceType() const {
2868  return isa<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
2869}
2870inline bool Type::isObjCQualifiedIdType() const {
2871  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2872    return OPT->isObjCQualifiedIdType();
2873  return false;
2874}
2875inline bool Type::isObjCQualifiedClassType() const {
2876  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2877    return OPT->isObjCQualifiedClassType();
2878  return false;
2879}
2880inline bool Type::isObjCIdType() const {
2881  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2882    return OPT->isObjCIdType();
2883  return false;
2884}
2885inline bool Type::isObjCClassType() const {
2886  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2887    return OPT->isObjCClassType();
2888  return false;
2889}
2890inline bool Type::isObjCBuiltinType() const {
2891  return isObjCIdType() || isObjCClassType();
2892}
2893inline bool Type::isTemplateTypeParmType() const {
2894  return isa<TemplateTypeParmType>(CanonicalType.getUnqualifiedType());
2895}
2896
2897inline bool Type::isSpecificBuiltinType(unsigned K) const {
2898  if (const BuiltinType *BT = getAs<BuiltinType>())
2899    if (BT->getKind() == (BuiltinType::Kind) K)
2900      return true;
2901  return false;
2902}
2903
2904/// \brief Determines whether this is a type for which one can define
2905/// an overloaded operator.
2906inline bool Type::isOverloadableType() const {
2907  return isDependentType() || isRecordType() || isEnumeralType();
2908}
2909
2910inline bool Type::hasPointerRepresentation() const {
2911  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
2912          isObjCInterfaceType() || isObjCObjectPointerType() ||
2913          isObjCQualifiedInterfaceType() || isNullPtrType());
2914}
2915
2916inline bool Type::hasObjCPointerRepresentation() const {
2917  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
2918          isObjCQualifiedInterfaceType());
2919}
2920
2921/// Insertion operator for diagnostics.  This allows sending QualType's into a
2922/// diagnostic with <<.
2923inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2924                                           QualType T) {
2925  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
2926                  Diagnostic::ak_qualtype);
2927  return DB;
2928}
2929
2930/// Member-template getAs<specific type>'.
2931template <typename T> const T *Type::getAs() const {
2932  // If this is directly a T type, return it.
2933  if (const T *Ty = dyn_cast<T>(this))
2934    return Ty;
2935
2936  // If the canonical form of this type isn't the right kind, reject it.
2937  if (!isa<T>(CanonicalType))
2938    return 0;
2939
2940  // If this is a typedef for the type, strip the typedef off without
2941  // losing all typedef information.
2942  return cast<T>(getUnqualifiedDesugaredType());
2943}
2944
2945}  // end namespace clang
2946
2947#endif
2948