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