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