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