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