Type.h revision 8eee119bf4f1693dde17b8552c1f9f81bf2b681e
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(ASTContext &Ctx) const;
853
854  /// \brief Determine whether this type is an integral or enumeration type.
855  bool isIntegralOrEnumerationType() const;
856
857  /// Floating point categories.
858  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
859  /// isComplexType() does *not* include complex integers (a GCC extension).
860  /// isComplexIntegerType() can be used to test for complex integers.
861  bool isComplexType() const;      // C99 6.2.5p11 (complex)
862  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
863  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
864  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
865  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
866  bool isVoidType() const;         // C99 6.2.5p19
867  bool isDerivedType() const;      // C99 6.2.5p20
868  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
869  bool isAggregateType() const;
870
871  // Type Predicates: Check to see if this type is structurally the specified
872  // type, ignoring typedefs and qualifiers.
873  bool isFunctionType() const;
874  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
875  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
876  bool isPointerType() const;
877  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
878  bool isBlockPointerType() const;
879  bool isVoidPointerType() const;
880  bool isReferenceType() const;
881  bool isLValueReferenceType() const;
882  bool isRValueReferenceType() const;
883  bool isFunctionPointerType() const;
884  bool isMemberPointerType() const;
885  bool isMemberFunctionPointerType() const;
886  bool isArrayType() const;
887  bool isConstantArrayType() const;
888  bool isIncompleteArrayType() const;
889  bool isVariableArrayType() const;
890  bool isDependentSizedArrayType() const;
891  bool isRecordType() const;
892  bool isClassType() const;
893  bool isStructureType() const;
894  bool isStructureOrClassType() const;
895  bool isUnionType() const;
896  bool isComplexIntegerType() const;            // GCC _Complex integer type.
897  bool isVectorType() const;                    // GCC vector type.
898  bool isExtVectorType() const;                 // Extended vector type.
899  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
900  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
901  // for the common case.
902  bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
903  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
904  bool isObjCQualifiedIdType() const;           // id<foo>
905  bool isObjCQualifiedClassType() const;        // Class<foo>
906  bool isObjCIdType() const;                    // id
907  bool isObjCClassType() const;                 // Class
908  bool isObjCSelType() const;                 // Class
909  bool isObjCBuiltinType() const;               // 'id' or 'Class'
910  bool isTemplateTypeParmType() const;          // C++ template type parameter
911  bool isNullPtrType() const;                   // C++0x nullptr_t
912
913  /// isDependentType - Whether this type is a dependent type, meaning
914  /// that its definition somehow depends on a template parameter
915  /// (C++ [temp.dep.type]).
916  bool isDependentType() const { return Dependent; }
917  bool isOverloadableType() const;
918
919  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
920  bool isElaboratedTypeSpecifier() const;
921
922  /// hasPointerRepresentation - Whether this type is represented
923  /// natively as a pointer; this includes pointers, references, block
924  /// pointers, and Objective-C interface, qualified id, and qualified
925  /// interface types, as well as nullptr_t.
926  bool hasPointerRepresentation() const;
927
928  /// hasObjCPointerRepresentation - Whether this type can represent
929  /// an objective pointer type for the purpose of GC'ability
930  bool hasObjCPointerRepresentation() const;
931
932  /// \brief Determine whether this type has a floating-point representation
933  /// of some sort, e.g., it is a floating-point type or a vector thereof.
934  bool hasFloatingRepresentation() const;
935
936  // Type Checking Functions: Check to see if this type is structurally the
937  // specified type, ignoring typedefs and qualifiers, and return a pointer to
938  // the best type we can.
939  const RecordType *getAsStructureType() const;
940  /// NOTE: getAs*ArrayType are methods on ASTContext.
941  const RecordType *getAsUnionType() const;
942  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
943  // The following is a convenience method that returns an ObjCObjectPointerType
944  // for object declared using an interface.
945  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
946  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
947  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
948  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
949
950  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
951  /// because the type is a RecordType or because it is the injected-class-name
952  /// type of a class template or class template partial specialization.
953  CXXRecordDecl *getAsCXXRecordDecl() const;
954
955  // Member-template getAs<specific type>'.  This scheme will eventually
956  // replace the specific getAsXXXX methods above.
957  //
958  // There are some specializations of this member template listed
959  // immediately following this class.
960  template <typename T> const T *getAs() const;
961
962  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
963  /// element type of the array, potentially with type qualifiers missing.
964  /// This method should never be used when type qualifiers are meaningful.
965  const Type *getArrayElementTypeNoTypeQual() const;
966
967  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
968  /// pointer, this returns the respective pointee.
969  QualType getPointeeType() const;
970
971  /// getUnqualifiedDesugaredType() - Return the specified type with
972  /// any "sugar" removed from the type, removing any typedefs,
973  /// typeofs, etc., as well as any qualifiers.
974  const Type *getUnqualifiedDesugaredType() const;
975
976  /// More type predicates useful for type checking/promotion
977  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
978
979  /// isSignedIntegerType - Return true if this is an integer type that is
980  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
981  /// an enum decl which has a signed representation, or a vector of signed
982  /// integer element type.
983  bool isSignedIntegerType() const;
984
985  /// isUnsignedIntegerType - Return true if this is an integer type that is
986  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
987  /// decl which has an unsigned representation, or a vector of unsigned integer
988  /// element type.
989  bool isUnsignedIntegerType() const;
990
991  /// isConstantSizeType - Return true if this is not a variable sized type,
992  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
993  /// incomplete types.
994  bool isConstantSizeType() const;
995
996  /// isSpecifierType - Returns true if this type can be represented by some
997  /// set of type specifiers.
998  bool isSpecifierType() const;
999
1000  /// \brief Determine the linkage of this type.
1001  Linkage getLinkage() const;
1002
1003  /// \brief Note that the linkage is no longer known.
1004  void ClearLinkageCache();
1005
1006  const char *getTypeClassName() const;
1007
1008  QualType getCanonicalTypeInternal() const {
1009    return CanonicalType;
1010  }
1011  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1012  void dump() const;
1013  static bool classof(const Type *) { return true; }
1014};
1015
1016template <> inline const TypedefType *Type::getAs() const {
1017  return dyn_cast<TypedefType>(this);
1018}
1019
1020// We can do canonical leaf types faster, because we don't have to
1021// worry about preserving child type decoration.
1022#define TYPE(Class, Base)
1023#define LEAF_TYPE(Class) \
1024template <> inline const Class##Type *Type::getAs() const { \
1025  return dyn_cast<Class##Type>(CanonicalType); \
1026}
1027#include "clang/AST/TypeNodes.def"
1028
1029
1030/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1031/// types are always canonical and have a literal name field.
1032class BuiltinType : public Type {
1033public:
1034  enum Kind {
1035    Void,
1036
1037    Bool,     // This is bool and/or _Bool.
1038    Char_U,   // This is 'char' for targets where char is unsigned.
1039    UChar,    // This is explicitly qualified unsigned char.
1040    Char16,   // This is 'char16_t' for C++.
1041    Char32,   // This is 'char32_t' for C++.
1042    UShort,
1043    UInt,
1044    ULong,
1045    ULongLong,
1046    UInt128,  // __uint128_t
1047
1048    Char_S,   // This is 'char' for targets where char is signed.
1049    SChar,    // This is explicitly qualified signed char.
1050    WChar,    // This is 'wchar_t' for C++.
1051    Short,
1052    Int,
1053    Long,
1054    LongLong,
1055    Int128,   // __int128_t
1056
1057    Float, Double, LongDouble,
1058
1059    NullPtr,  // This is the type of C++0x 'nullptr'.
1060
1061    Overload,  // This represents the type of an overloaded function declaration.
1062    Dependent, // This represents the type of a type-dependent expression.
1063
1064    UndeducedAuto, // In C++0x, this represents the type of an auto variable
1065                   // that has not been deduced yet.
1066
1067    /// The primitive Objective C 'id' type.  The type pointed to by the
1068    /// user-visible 'id' type.  Only ever shows up in an AST as the base
1069    /// type of an ObjCObjectType.
1070    ObjCId,
1071
1072    /// The primitive Objective C 'Class' type.  The type pointed to by the
1073    /// user-visible 'Class' type.  Only ever shows up in an AST as the
1074    /// base type of an ObjCObjectType.
1075    ObjCClass,
1076
1077    ObjCSel    // This represents the ObjC 'SEL' type.
1078  };
1079private:
1080  Kind TypeKind;
1081
1082protected:
1083  virtual Linkage getLinkageImpl() const;
1084
1085public:
1086  BuiltinType(Kind K)
1087    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
1088      TypeKind(K) {}
1089
1090  Kind getKind() const { return TypeKind; }
1091  const char *getName(const LangOptions &LO) const;
1092
1093  bool isSugared() const { return false; }
1094  QualType desugar() const { return QualType(this, 0); }
1095
1096  bool isInteger() const {
1097    return TypeKind >= Bool && TypeKind <= Int128;
1098  }
1099
1100  bool isSignedInteger() const {
1101    return TypeKind >= Char_S && TypeKind <= Int128;
1102  }
1103
1104  bool isUnsignedInteger() const {
1105    return TypeKind >= Bool && TypeKind <= UInt128;
1106  }
1107
1108  bool isFloatingPoint() const {
1109    return TypeKind >= Float && TypeKind <= LongDouble;
1110  }
1111
1112  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1113  static bool classof(const BuiltinType *) { return true; }
1114};
1115
1116/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1117/// types (_Complex float etc) as well as the GCC integer complex extensions.
1118///
1119class ComplexType : public Type, public llvm::FoldingSetNode {
1120  QualType ElementType;
1121  ComplexType(QualType Element, QualType CanonicalPtr) :
1122    Type(Complex, CanonicalPtr, Element->isDependentType()),
1123    ElementType(Element) {
1124  }
1125  friend class ASTContext;  // ASTContext creates these.
1126
1127protected:
1128  virtual Linkage getLinkageImpl() const;
1129
1130public:
1131  QualType getElementType() const { return ElementType; }
1132
1133  bool isSugared() const { return false; }
1134  QualType desugar() const { return QualType(this, 0); }
1135
1136  void Profile(llvm::FoldingSetNodeID &ID) {
1137    Profile(ID, getElementType());
1138  }
1139  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1140    ID.AddPointer(Element.getAsOpaquePtr());
1141  }
1142
1143  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1144  static bool classof(const ComplexType *) { return true; }
1145};
1146
1147/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1148///
1149class PointerType : public Type, public llvm::FoldingSetNode {
1150  QualType PointeeType;
1151
1152  PointerType(QualType Pointee, QualType CanonicalPtr) :
1153    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1154  }
1155  friend class ASTContext;  // ASTContext creates these.
1156
1157protected:
1158  virtual Linkage getLinkageImpl() const;
1159
1160public:
1161
1162  QualType getPointeeType() const { return PointeeType; }
1163
1164  bool isSugared() const { return false; }
1165  QualType desugar() const { return QualType(this, 0); }
1166
1167  void Profile(llvm::FoldingSetNodeID &ID) {
1168    Profile(ID, getPointeeType());
1169  }
1170  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1171    ID.AddPointer(Pointee.getAsOpaquePtr());
1172  }
1173
1174  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1175  static bool classof(const PointerType *) { return true; }
1176};
1177
1178/// BlockPointerType - pointer to a block type.
1179/// This type is to represent types syntactically represented as
1180/// "void (^)(int)", etc. Pointee is required to always be a function type.
1181///
1182class BlockPointerType : public Type, public llvm::FoldingSetNode {
1183  QualType PointeeType;  // Block is some kind of pointer type
1184  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1185    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1186    PointeeType(Pointee) {
1187  }
1188  friend class ASTContext;  // ASTContext creates these.
1189
1190protected:
1191  virtual Linkage getLinkageImpl() const;
1192
1193public:
1194
1195  // Get the pointee type. Pointee is required to always be a function type.
1196  QualType getPointeeType() const { return PointeeType; }
1197
1198  bool isSugared() const { return false; }
1199  QualType desugar() const { return QualType(this, 0); }
1200
1201  void Profile(llvm::FoldingSetNodeID &ID) {
1202      Profile(ID, getPointeeType());
1203  }
1204  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1205      ID.AddPointer(Pointee.getAsOpaquePtr());
1206  }
1207
1208  static bool classof(const Type *T) {
1209    return T->getTypeClass() == BlockPointer;
1210  }
1211  static bool classof(const BlockPointerType *) { return true; }
1212};
1213
1214/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1215///
1216class ReferenceType : public Type, public llvm::FoldingSetNode {
1217  QualType PointeeType;
1218
1219  /// True if the type was originally spelled with an lvalue sigil.
1220  /// This is never true of rvalue references but can also be false
1221  /// on lvalue references because of C++0x [dcl.typedef]p9,
1222  /// as follows:
1223  ///
1224  ///   typedef int &ref;    // lvalue, spelled lvalue
1225  ///   typedef int &&rvref; // rvalue
1226  ///   ref &a;              // lvalue, inner ref, spelled lvalue
1227  ///   ref &&a;             // lvalue, inner ref
1228  ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1229  ///   rvref &&a;           // rvalue, inner ref
1230  bool SpelledAsLValue;
1231
1232  /// True if the inner type is a reference type.  This only happens
1233  /// in non-canonical forms.
1234  bool InnerRef;
1235
1236protected:
1237  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1238                bool SpelledAsLValue) :
1239    Type(tc, CanonicalRef, Referencee->isDependentType()),
1240    PointeeType(Referencee), SpelledAsLValue(SpelledAsLValue),
1241    InnerRef(Referencee->isReferenceType()) {
1242  }
1243
1244  virtual Linkage getLinkageImpl() const;
1245
1246public:
1247  bool isSpelledAsLValue() const { return SpelledAsLValue; }
1248  bool isInnerRef() const { return InnerRef; }
1249
1250  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1251  QualType getPointeeType() const {
1252    // FIXME: this might strip inner qualifiers; okay?
1253    const ReferenceType *T = this;
1254    while (T->InnerRef)
1255      T = T->PointeeType->getAs<ReferenceType>();
1256    return T->PointeeType;
1257  }
1258
1259  void Profile(llvm::FoldingSetNodeID &ID) {
1260    Profile(ID, PointeeType, SpelledAsLValue);
1261  }
1262  static void Profile(llvm::FoldingSetNodeID &ID,
1263                      QualType Referencee,
1264                      bool SpelledAsLValue) {
1265    ID.AddPointer(Referencee.getAsOpaquePtr());
1266    ID.AddBoolean(SpelledAsLValue);
1267  }
1268
1269  static bool classof(const Type *T) {
1270    return T->getTypeClass() == LValueReference ||
1271           T->getTypeClass() == RValueReference;
1272  }
1273  static bool classof(const ReferenceType *) { return true; }
1274};
1275
1276/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1277///
1278class LValueReferenceType : public ReferenceType {
1279  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1280                      bool SpelledAsLValue) :
1281    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1282  {}
1283  friend class ASTContext; // ASTContext creates these
1284public:
1285  bool isSugared() const { return false; }
1286  QualType desugar() const { return QualType(this, 0); }
1287
1288  static bool classof(const Type *T) {
1289    return T->getTypeClass() == LValueReference;
1290  }
1291  static bool classof(const LValueReferenceType *) { return true; }
1292};
1293
1294/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1295///
1296class RValueReferenceType : public ReferenceType {
1297  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1298    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1299  }
1300  friend class ASTContext; // ASTContext creates these
1301public:
1302  bool isSugared() const { return false; }
1303  QualType desugar() const { return QualType(this, 0); }
1304
1305  static bool classof(const Type *T) {
1306    return T->getTypeClass() == RValueReference;
1307  }
1308  static bool classof(const RValueReferenceType *) { return true; }
1309};
1310
1311/// MemberPointerType - C++ 8.3.3 - Pointers to members
1312///
1313class MemberPointerType : public Type, public llvm::FoldingSetNode {
1314  QualType PointeeType;
1315  /// The class of which the pointee is a member. Must ultimately be a
1316  /// RecordType, but could be a typedef or a template parameter too.
1317  const Type *Class;
1318
1319  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1320    Type(MemberPointer, CanonicalPtr,
1321         Cls->isDependentType() || Pointee->isDependentType()),
1322    PointeeType(Pointee), Class(Cls) {
1323  }
1324  friend class ASTContext; // ASTContext creates these.
1325
1326protected:
1327  virtual Linkage getLinkageImpl() const;
1328
1329public:
1330
1331  QualType getPointeeType() const { return PointeeType; }
1332
1333  const Type *getClass() const { return Class; }
1334
1335  bool isSugared() const { return false; }
1336  QualType desugar() const { return QualType(this, 0); }
1337
1338  void Profile(llvm::FoldingSetNodeID &ID) {
1339    Profile(ID, getPointeeType(), getClass());
1340  }
1341  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1342                      const Type *Class) {
1343    ID.AddPointer(Pointee.getAsOpaquePtr());
1344    ID.AddPointer(Class);
1345  }
1346
1347  static bool classof(const Type *T) {
1348    return T->getTypeClass() == MemberPointer;
1349  }
1350  static bool classof(const MemberPointerType *) { return true; }
1351};
1352
1353/// ArrayType - C99 6.7.5.2 - Array Declarators.
1354///
1355class ArrayType : public Type, public llvm::FoldingSetNode {
1356public:
1357  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1358  /// an array with a static size (e.g. int X[static 4]), or an array
1359  /// with a star size (e.g. int X[*]).
1360  /// 'static' is only allowed on function parameters.
1361  enum ArraySizeModifier {
1362    Normal, Static, Star
1363  };
1364private:
1365  /// ElementType - The element type of the array.
1366  QualType ElementType;
1367
1368  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1369  /// NOTE: These fields are packed into the bitfields space in the Type class.
1370  unsigned SizeModifier : 2;
1371
1372  /// IndexTypeQuals - Capture qualifiers in declarations like:
1373  /// 'int X[static restrict 4]'. For function parameters only.
1374  unsigned IndexTypeQuals : 3;
1375
1376protected:
1377  // C++ [temp.dep.type]p1:
1378  //   A type is dependent if it is...
1379  //     - an array type constructed from any dependent type or whose
1380  //       size is specified by a constant expression that is
1381  //       value-dependent,
1382  ArrayType(TypeClass tc, QualType et, QualType can,
1383            ArraySizeModifier sm, unsigned tq)
1384    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1385      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1386
1387  friend class ASTContext;  // ASTContext creates these.
1388
1389  virtual Linkage getLinkageImpl() const;
1390
1391public:
1392  QualType getElementType() const { return ElementType; }
1393  ArraySizeModifier getSizeModifier() const {
1394    return ArraySizeModifier(SizeModifier);
1395  }
1396  Qualifiers getIndexTypeQualifiers() const {
1397    return Qualifiers::fromCVRMask(IndexTypeQuals);
1398  }
1399  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1400
1401  static bool classof(const Type *T) {
1402    return T->getTypeClass() == ConstantArray ||
1403           T->getTypeClass() == VariableArray ||
1404           T->getTypeClass() == IncompleteArray ||
1405           T->getTypeClass() == DependentSizedArray;
1406  }
1407  static bool classof(const ArrayType *) { return true; }
1408};
1409
1410/// ConstantArrayType - This class represents the canonical version of
1411/// C arrays with a specified constant size.  For example, the canonical
1412/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1413/// type is 'int' and the size is 404.
1414class ConstantArrayType : public ArrayType {
1415  llvm::APInt Size; // Allows us to unique the type.
1416
1417  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1418                    ArraySizeModifier sm, unsigned tq)
1419    : ArrayType(ConstantArray, et, can, sm, tq),
1420      Size(size) {}
1421protected:
1422  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1423                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1424    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1425  friend class ASTContext;  // ASTContext creates these.
1426public:
1427  const llvm::APInt &getSize() const { return Size; }
1428  bool isSugared() const { return false; }
1429  QualType desugar() const { return QualType(this, 0); }
1430
1431  void Profile(llvm::FoldingSetNodeID &ID) {
1432    Profile(ID, getElementType(), getSize(),
1433            getSizeModifier(), getIndexTypeCVRQualifiers());
1434  }
1435  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1436                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1437                      unsigned TypeQuals) {
1438    ID.AddPointer(ET.getAsOpaquePtr());
1439    ID.AddInteger(ArraySize.getZExtValue());
1440    ID.AddInteger(SizeMod);
1441    ID.AddInteger(TypeQuals);
1442  }
1443  static bool classof(const Type *T) {
1444    return T->getTypeClass() == ConstantArray;
1445  }
1446  static bool classof(const ConstantArrayType *) { return true; }
1447};
1448
1449/// IncompleteArrayType - This class represents C arrays with an unspecified
1450/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1451/// type is 'int' and the size is unspecified.
1452class IncompleteArrayType : public ArrayType {
1453
1454  IncompleteArrayType(QualType et, QualType can,
1455                      ArraySizeModifier sm, unsigned tq)
1456    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1457  friend class ASTContext;  // ASTContext creates these.
1458public:
1459  bool isSugared() const { return false; }
1460  QualType desugar() const { return QualType(this, 0); }
1461
1462  static bool classof(const Type *T) {
1463    return T->getTypeClass() == IncompleteArray;
1464  }
1465  static bool classof(const IncompleteArrayType *) { return true; }
1466
1467  friend class StmtIteratorBase;
1468
1469  void Profile(llvm::FoldingSetNodeID &ID) {
1470    Profile(ID, getElementType(), getSizeModifier(),
1471            getIndexTypeCVRQualifiers());
1472  }
1473
1474  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1475                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1476    ID.AddPointer(ET.getAsOpaquePtr());
1477    ID.AddInteger(SizeMod);
1478    ID.AddInteger(TypeQuals);
1479  }
1480};
1481
1482/// VariableArrayType - This class represents C arrays with a specified size
1483/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1484/// Since the size expression is an arbitrary expression, we store it as such.
1485///
1486/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1487/// should not be: two lexically equivalent variable array types could mean
1488/// different things, for example, these variables do not have the same type
1489/// dynamically:
1490///
1491/// void foo(int x) {
1492///   int Y[x];
1493///   ++x;
1494///   int Z[x];
1495/// }
1496///
1497class VariableArrayType : public ArrayType {
1498  /// SizeExpr - An assignment expression. VLA's are only permitted within
1499  /// a function block.
1500  Stmt *SizeExpr;
1501  /// Brackets - The left and right array brackets.
1502  SourceRange Brackets;
1503
1504  VariableArrayType(QualType et, QualType can, Expr *e,
1505                    ArraySizeModifier sm, unsigned tq,
1506                    SourceRange brackets)
1507    : ArrayType(VariableArray, et, can, sm, tq),
1508      SizeExpr((Stmt*) e), Brackets(brackets) {}
1509  friend class ASTContext;  // ASTContext creates these.
1510  virtual void Destroy(ASTContext& C);
1511
1512public:
1513  Expr *getSizeExpr() const {
1514    // We use C-style casts instead of cast<> here because we do not wish
1515    // to have a dependency of Type.h on Stmt.h/Expr.h.
1516    return (Expr*) SizeExpr;
1517  }
1518  SourceRange getBracketsRange() const { return Brackets; }
1519  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1520  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1521
1522  bool isSugared() const { return false; }
1523  QualType desugar() const { return QualType(this, 0); }
1524
1525  static bool classof(const Type *T) {
1526    return T->getTypeClass() == VariableArray;
1527  }
1528  static bool classof(const VariableArrayType *) { return true; }
1529
1530  friend class StmtIteratorBase;
1531
1532  void Profile(llvm::FoldingSetNodeID &ID) {
1533    assert(0 && "Cannnot unique VariableArrayTypes.");
1534  }
1535};
1536
1537/// DependentSizedArrayType - This type represents an array type in
1538/// C++ whose size is a value-dependent expression. For example:
1539///
1540/// \code
1541/// template<typename T, int Size>
1542/// class array {
1543///   T data[Size];
1544/// };
1545/// \endcode
1546///
1547/// For these types, we won't actually know what the array bound is
1548/// until template instantiation occurs, at which point this will
1549/// become either a ConstantArrayType or a VariableArrayType.
1550class DependentSizedArrayType : public ArrayType {
1551  ASTContext &Context;
1552
1553  /// \brief An assignment expression that will instantiate to the
1554  /// size of the array.
1555  ///
1556  /// The expression itself might be NULL, in which case the array
1557  /// type will have its size deduced from an initializer.
1558  Stmt *SizeExpr;
1559
1560  /// Brackets - The left and right array brackets.
1561  SourceRange Brackets;
1562
1563  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1564                          Expr *e, ArraySizeModifier sm, unsigned tq,
1565                          SourceRange brackets)
1566    : ArrayType(DependentSizedArray, et, can, sm, tq),
1567      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1568  friend class ASTContext;  // ASTContext creates these.
1569  virtual void Destroy(ASTContext& C);
1570
1571public:
1572  Expr *getSizeExpr() const {
1573    // We use C-style casts instead of cast<> here because we do not wish
1574    // to have a dependency of Type.h on Stmt.h/Expr.h.
1575    return (Expr*) SizeExpr;
1576  }
1577  SourceRange getBracketsRange() const { return Brackets; }
1578  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1579  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1580
1581  bool isSugared() const { return false; }
1582  QualType desugar() const { return QualType(this, 0); }
1583
1584  static bool classof(const Type *T) {
1585    return T->getTypeClass() == DependentSizedArray;
1586  }
1587  static bool classof(const DependentSizedArrayType *) { return true; }
1588
1589  friend class StmtIteratorBase;
1590
1591
1592  void Profile(llvm::FoldingSetNodeID &ID) {
1593    Profile(ID, Context, getElementType(),
1594            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1595  }
1596
1597  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1598                      QualType ET, ArraySizeModifier SizeMod,
1599                      unsigned TypeQuals, Expr *E);
1600};
1601
1602/// DependentSizedExtVectorType - This type represent an extended vector type
1603/// where either the type or size is dependent. For example:
1604/// @code
1605/// template<typename T, int Size>
1606/// class vector {
1607///   typedef T __attribute__((ext_vector_type(Size))) type;
1608/// }
1609/// @endcode
1610class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1611  ASTContext &Context;
1612  Expr *SizeExpr;
1613  /// ElementType - The element type of the array.
1614  QualType ElementType;
1615  SourceLocation loc;
1616
1617  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1618                              QualType can, Expr *SizeExpr, SourceLocation loc)
1619    : Type (DependentSizedExtVector, can, true),
1620      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1621      loc(loc) {}
1622  friend class ASTContext;
1623  virtual void Destroy(ASTContext& C);
1624
1625public:
1626  Expr *getSizeExpr() const { return SizeExpr; }
1627  QualType getElementType() const { return ElementType; }
1628  SourceLocation getAttributeLoc() const { return loc; }
1629
1630  bool isSugared() const { return false; }
1631  QualType desugar() const { return QualType(this, 0); }
1632
1633  static bool classof(const Type *T) {
1634    return T->getTypeClass() == DependentSizedExtVector;
1635  }
1636  static bool classof(const DependentSizedExtVectorType *) { return true; }
1637
1638  void Profile(llvm::FoldingSetNodeID &ID) {
1639    Profile(ID, Context, getElementType(), getSizeExpr());
1640  }
1641
1642  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1643                      QualType ElementType, Expr *SizeExpr);
1644};
1645
1646
1647/// VectorType - GCC generic vector type. This type is created using
1648/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1649/// bytes; or from an Altivec __vector or vector declaration.
1650/// Since the constructor takes the number of vector elements, the
1651/// client is responsible for converting the size into the number of elements.
1652class VectorType : public Type, public llvm::FoldingSetNode {
1653protected:
1654  /// ElementType - The element type of the vector.
1655  QualType ElementType;
1656
1657  /// NumElements - The number of elements in the vector.
1658  unsigned NumElements;
1659
1660  /// AltiVec - True if this is for an Altivec vector.
1661  bool AltiVec;
1662
1663  /// Pixel - True if this is for an Altivec vector pixel.
1664  bool Pixel;
1665
1666  VectorType(QualType vecType, unsigned nElements, QualType canonType,
1667      bool isAltiVec, bool isPixel) :
1668    Type(Vector, canonType, vecType->isDependentType()),
1669    ElementType(vecType), NumElements(nElements),
1670    AltiVec(isAltiVec), Pixel(isPixel) {}
1671  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1672             QualType canonType, bool isAltiVec, bool isPixel)
1673    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1674      NumElements(nElements), AltiVec(isAltiVec), Pixel(isPixel) {}
1675  friend class ASTContext;  // ASTContext creates these.
1676
1677  virtual Linkage getLinkageImpl() const;
1678
1679public:
1680
1681  QualType getElementType() const { return ElementType; }
1682  unsigned getNumElements() const { return NumElements; }
1683
1684  bool isSugared() const { return false; }
1685  QualType desugar() const { return QualType(this, 0); }
1686
1687  bool isAltiVec() const { return AltiVec; }
1688
1689  bool isPixel() const { return Pixel; }
1690
1691  void Profile(llvm::FoldingSetNodeID &ID) {
1692    Profile(ID, getElementType(), getNumElements(), getTypeClass(),
1693      AltiVec, Pixel);
1694  }
1695  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1696                      unsigned NumElements, TypeClass TypeClass,
1697                      bool isAltiVec, bool isPixel) {
1698    ID.AddPointer(ElementType.getAsOpaquePtr());
1699    ID.AddInteger(NumElements);
1700    ID.AddInteger(TypeClass);
1701    ID.AddBoolean(isAltiVec);
1702    ID.AddBoolean(isPixel);
1703  }
1704
1705  static bool classof(const Type *T) {
1706    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1707  }
1708  static bool classof(const VectorType *) { return true; }
1709};
1710
1711/// ExtVectorType - Extended vector type. This type is created using
1712/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1713/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1714/// class enables syntactic extensions, like Vector Components for accessing
1715/// points, colors, and textures (modeled after OpenGL Shading Language).
1716class ExtVectorType : public VectorType {
1717  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1718    VectorType(ExtVector, vecType, nElements, canonType, false, false) {}
1719  friend class ASTContext;  // ASTContext creates these.
1720public:
1721  static int getPointAccessorIdx(char c) {
1722    switch (c) {
1723    default: return -1;
1724    case 'x': return 0;
1725    case 'y': return 1;
1726    case 'z': return 2;
1727    case 'w': return 3;
1728    }
1729  }
1730  static int getNumericAccessorIdx(char c) {
1731    switch (c) {
1732      default: return -1;
1733      case '0': return 0;
1734      case '1': return 1;
1735      case '2': return 2;
1736      case '3': return 3;
1737      case '4': return 4;
1738      case '5': return 5;
1739      case '6': return 6;
1740      case '7': return 7;
1741      case '8': return 8;
1742      case '9': return 9;
1743      case 'A':
1744      case 'a': return 10;
1745      case 'B':
1746      case 'b': return 11;
1747      case 'C':
1748      case 'c': return 12;
1749      case 'D':
1750      case 'd': return 13;
1751      case 'E':
1752      case 'e': return 14;
1753      case 'F':
1754      case 'f': return 15;
1755    }
1756  }
1757
1758  static int getAccessorIdx(char c) {
1759    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1760    return getNumericAccessorIdx(c);
1761  }
1762
1763  bool isAccessorWithinNumElements(char c) const {
1764    if (int idx = getAccessorIdx(c)+1)
1765      return unsigned(idx-1) < NumElements;
1766    return false;
1767  }
1768  bool isSugared() const { return false; }
1769  QualType desugar() const { return QualType(this, 0); }
1770
1771  static bool classof(const Type *T) {
1772    return T->getTypeClass() == ExtVector;
1773  }
1774  static bool classof(const ExtVectorType *) { return true; }
1775};
1776
1777/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1778/// class of FunctionNoProtoType and FunctionProtoType.
1779///
1780class FunctionType : public Type {
1781  virtual void ANCHOR(); // Key function for FunctionType.
1782
1783  /// SubClassData - This field is owned by the subclass, put here to pack
1784  /// tightly with the ivars in Type.
1785  bool SubClassData : 1;
1786
1787  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1788  /// other bitfields.
1789  /// The qualifiers are part of FunctionProtoType because...
1790  ///
1791  /// C++ 8.3.5p4: The return type, the parameter type list and the
1792  /// cv-qualifier-seq, [...], are part of the function type.
1793  ///
1794  unsigned TypeQuals : 3;
1795
1796  /// NoReturn - Indicates if the function type is attribute noreturn.
1797  unsigned NoReturn : 1;
1798
1799  /// RegParm - How many arguments to pass inreg.
1800  unsigned RegParm : 3;
1801
1802  /// CallConv - The calling convention used by the function.
1803  unsigned CallConv : 3;
1804
1805  // The type returned by the function.
1806  QualType ResultType;
1807
1808 public:
1809  // This class is used for passing arround the information needed to
1810  // construct a call. It is not actually used for storage, just for
1811  // factoring together common arguments.
1812  // If you add a field (say Foo), other than the obvious places (both, constructors,
1813  // compile failures), what you need to update is
1814  // * Operetor==
1815  // * getFoo
1816  // * withFoo
1817  // * functionType. Add Foo, getFoo.
1818  // * ASTContext::getFooType
1819  // * ASTContext::mergeFunctionTypes
1820  // * FunctionNoProtoType::Profile
1821  // * FunctionProtoType::Profile
1822  // * TypePrinter::PrintFunctionProto
1823  // * PCH read and write
1824  // * Codegen
1825
1826  class ExtInfo {
1827   public:
1828    // Constructor with no defaults. Use this when you know that you
1829    // have all the elements (when reading a PCH file for example).
1830    ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) :
1831        NoReturn(noReturn), RegParm(regParm), CC(cc) {}
1832
1833    // Constructor with all defaults. Use when for example creating a
1834    // function know to use defaults.
1835    ExtInfo() : NoReturn(false), RegParm(0), CC(CC_Default) {}
1836
1837    bool getNoReturn() const { return NoReturn; }
1838    unsigned getRegParm() const { return RegParm; }
1839    CallingConv getCC() const { return CC; }
1840
1841    bool operator==(const ExtInfo &Other) const {
1842      return getNoReturn() == Other.getNoReturn() &&
1843          getRegParm() == Other.getRegParm() &&
1844          getCC() == Other.getCC();
1845    }
1846    bool operator!=(const ExtInfo &Other) const {
1847      return !(*this == Other);
1848    }
1849
1850    // Note that we don't have setters. That is by design, use
1851    // the following with methods instead of mutating these objects.
1852
1853    ExtInfo withNoReturn(bool noReturn) const {
1854      return ExtInfo(noReturn, getRegParm(), getCC());
1855    }
1856
1857    ExtInfo withRegParm(unsigned RegParm) const {
1858      return ExtInfo(getNoReturn(), RegParm, getCC());
1859    }
1860
1861    ExtInfo withCallingConv(CallingConv cc) const {
1862      return ExtInfo(getNoReturn(), getRegParm(), cc);
1863    }
1864
1865   private:
1866    // True if we have __attribute__((noreturn))
1867    bool NoReturn;
1868    // The value passed to __attribute__((regparm(x)))
1869    unsigned RegParm;
1870    // The calling convention as specified via
1871    // __attribute__((cdecl|stdcall|fastcall|thiscall))
1872    CallingConv CC;
1873  };
1874
1875protected:
1876  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1877               unsigned typeQuals, QualType Canonical, bool Dependent,
1878               const ExtInfo &Info)
1879    : Type(tc, Canonical, Dependent),
1880      SubClassData(SubclassInfo), TypeQuals(typeQuals),
1881      NoReturn(Info.getNoReturn()),
1882      RegParm(Info.getRegParm()), CallConv(Info.getCC()), ResultType(res) {}
1883  bool getSubClassData() const { return SubClassData; }
1884  unsigned getTypeQuals() const { return TypeQuals; }
1885public:
1886
1887  QualType getResultType() const { return ResultType; }
1888  unsigned getRegParmType() const { return RegParm; }
1889  bool getNoReturnAttr() const { return NoReturn; }
1890  CallingConv getCallConv() const { return (CallingConv)CallConv; }
1891  ExtInfo getExtInfo() const {
1892    return ExtInfo(NoReturn, RegParm, (CallingConv)CallConv);
1893  }
1894
1895  static llvm::StringRef getNameForCallConv(CallingConv CC);
1896
1897  static bool classof(const Type *T) {
1898    return T->getTypeClass() == FunctionNoProto ||
1899           T->getTypeClass() == FunctionProto;
1900  }
1901  static bool classof(const FunctionType *) { return true; }
1902};
1903
1904/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1905/// no information available about its arguments.
1906class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1907  FunctionNoProtoType(QualType Result, QualType Canonical,
1908                      const ExtInfo &Info)
1909    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1910                   /*Dependent=*/false, Info) {}
1911  friend class ASTContext;  // ASTContext creates these.
1912
1913protected:
1914  virtual Linkage getLinkageImpl() const;
1915
1916public:
1917  // No additional state past what FunctionType provides.
1918
1919  bool isSugared() const { return false; }
1920  QualType desugar() const { return QualType(this, 0); }
1921
1922  void Profile(llvm::FoldingSetNodeID &ID) {
1923    Profile(ID, getResultType(), getExtInfo());
1924  }
1925  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1926                      const ExtInfo &Info) {
1927    ID.AddInteger(Info.getCC());
1928    ID.AddInteger(Info.getRegParm());
1929    ID.AddInteger(Info.getNoReturn());
1930    ID.AddPointer(ResultType.getAsOpaquePtr());
1931  }
1932
1933  static bool classof(const Type *T) {
1934    return T->getTypeClass() == FunctionNoProto;
1935  }
1936  static bool classof(const FunctionNoProtoType *) { return true; }
1937};
1938
1939/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1940/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1941/// arguments, not as having a single void argument. Such a type can have an
1942/// exception specification, but this specification is not part of the canonical
1943/// type.
1944class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1945  /// hasAnyDependentType - Determine whether there are any dependent
1946  /// types within the arguments passed in.
1947  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1948    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1949      if (ArgArray[Idx]->isDependentType())
1950    return true;
1951
1952    return false;
1953  }
1954
1955  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1956                    bool isVariadic, unsigned typeQuals, bool hasExs,
1957                    bool hasAnyExs, const QualType *ExArray,
1958                    unsigned numExs, QualType Canonical,
1959                    const ExtInfo &Info)
1960    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1961                   (Result->isDependentType() ||
1962                    hasAnyDependentType(ArgArray, numArgs)),
1963                   Info),
1964      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1965      AnyExceptionSpec(hasAnyExs) {
1966    // Fill in the trailing argument array.
1967    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1968    for (unsigned i = 0; i != numArgs; ++i)
1969      ArgInfo[i] = ArgArray[i];
1970    // Fill in the exception array.
1971    QualType *Ex = ArgInfo + numArgs;
1972    for (unsigned i = 0; i != numExs; ++i)
1973      Ex[i] = ExArray[i];
1974  }
1975
1976  /// NumArgs - The number of arguments this function has, not counting '...'.
1977  unsigned NumArgs : 20;
1978
1979  /// NumExceptions - The number of types in the exception spec, if any.
1980  unsigned NumExceptions : 10;
1981
1982  /// HasExceptionSpec - Whether this function has an exception spec at all.
1983  bool HasExceptionSpec : 1;
1984
1985  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1986  bool AnyExceptionSpec : 1;
1987
1988  /// ArgInfo - There is an variable size array after the class in memory that
1989  /// holds the argument types.
1990
1991  /// Exceptions - There is another variable size array after ArgInfo that
1992  /// holds the exception types.
1993
1994  friend class ASTContext;  // ASTContext creates these.
1995
1996protected:
1997  virtual Linkage getLinkageImpl() const;
1998
1999public:
2000  unsigned getNumArgs() const { return NumArgs; }
2001  QualType getArgType(unsigned i) const {
2002    assert(i < NumArgs && "Invalid argument number!");
2003    return arg_type_begin()[i];
2004  }
2005
2006  bool hasExceptionSpec() const { return HasExceptionSpec; }
2007  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
2008  unsigned getNumExceptions() const { return NumExceptions; }
2009  QualType getExceptionType(unsigned i) const {
2010    assert(i < NumExceptions && "Invalid exception number!");
2011    return exception_begin()[i];
2012  }
2013  bool hasEmptyExceptionSpec() const {
2014    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
2015      getNumExceptions() == 0;
2016  }
2017
2018  bool isVariadic() const { return getSubClassData(); }
2019  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2020
2021  typedef const QualType *arg_type_iterator;
2022  arg_type_iterator arg_type_begin() const {
2023    return reinterpret_cast<const QualType *>(this+1);
2024  }
2025  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2026
2027  typedef const QualType *exception_iterator;
2028  exception_iterator exception_begin() const {
2029    // exceptions begin where arguments end
2030    return arg_type_end();
2031  }
2032  exception_iterator exception_end() const {
2033    return exception_begin() + NumExceptions;
2034  }
2035
2036  bool isSugared() const { return false; }
2037  QualType desugar() const { return QualType(this, 0); }
2038
2039  static bool classof(const Type *T) {
2040    return T->getTypeClass() == FunctionProto;
2041  }
2042  static bool classof(const FunctionProtoType *) { return true; }
2043
2044  void Profile(llvm::FoldingSetNodeID &ID);
2045  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2046                      arg_type_iterator ArgTys, unsigned NumArgs,
2047                      bool isVariadic, unsigned TypeQuals,
2048                      bool hasExceptionSpec, bool anyExceptionSpec,
2049                      unsigned NumExceptions, exception_iterator Exs,
2050                      const ExtInfo &ExtInfo);
2051};
2052
2053
2054/// \brief Represents the dependent type named by a dependently-scoped
2055/// typename using declaration, e.g.
2056///   using typename Base<T>::foo;
2057/// Template instantiation turns these into the underlying type.
2058class UnresolvedUsingType : public Type {
2059  UnresolvedUsingTypenameDecl *Decl;
2060
2061  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2062    : Type(UnresolvedUsing, QualType(), true),
2063      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2064  friend class ASTContext; // ASTContext creates these.
2065public:
2066
2067  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2068
2069  bool isSugared() const { return false; }
2070  QualType desugar() const { return QualType(this, 0); }
2071
2072  static bool classof(const Type *T) {
2073    return T->getTypeClass() == UnresolvedUsing;
2074  }
2075  static bool classof(const UnresolvedUsingType *) { return true; }
2076
2077  void Profile(llvm::FoldingSetNodeID &ID) {
2078    return Profile(ID, Decl);
2079  }
2080  static void Profile(llvm::FoldingSetNodeID &ID,
2081                      UnresolvedUsingTypenameDecl *D) {
2082    ID.AddPointer(D);
2083  }
2084};
2085
2086
2087class TypedefType : public Type {
2088  TypedefDecl *Decl;
2089protected:
2090  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2091    : Type(tc, can, can->isDependentType()),
2092      Decl(const_cast<TypedefDecl*>(D)) {
2093    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2094  }
2095  friend class ASTContext;  // ASTContext creates these.
2096public:
2097
2098  TypedefDecl *getDecl() const { return Decl; }
2099
2100  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
2101  /// potentially looking through *all* consecutive typedefs.  This returns the
2102  /// sum of the type qualifiers, so if you have:
2103  ///   typedef const int A;
2104  ///   typedef volatile A B;
2105  /// looking through the typedefs for B will give you "const volatile A".
2106  QualType LookThroughTypedefs() const;
2107
2108  bool isSugared() const { return true; }
2109  QualType desugar() const;
2110
2111  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2112  static bool classof(const TypedefType *) { return true; }
2113};
2114
2115/// TypeOfExprType (GCC extension).
2116class TypeOfExprType : public Type {
2117  Expr *TOExpr;
2118
2119protected:
2120  TypeOfExprType(Expr *E, QualType can = QualType());
2121  friend class ASTContext;  // ASTContext creates these.
2122public:
2123  Expr *getUnderlyingExpr() const { return TOExpr; }
2124
2125  /// \brief Remove a single level of sugar.
2126  QualType desugar() const;
2127
2128  /// \brief Returns whether this type directly provides sugar.
2129  bool isSugared() const { return true; }
2130
2131  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2132  static bool classof(const TypeOfExprType *) { return true; }
2133};
2134
2135/// \brief Internal representation of canonical, dependent
2136/// typeof(expr) types.
2137///
2138/// This class is used internally by the ASTContext to manage
2139/// canonical, dependent types, only. Clients will only see instances
2140/// of this class via TypeOfExprType nodes.
2141class DependentTypeOfExprType
2142  : public TypeOfExprType, public llvm::FoldingSetNode {
2143  ASTContext &Context;
2144
2145public:
2146  DependentTypeOfExprType(ASTContext &Context, Expr *E)
2147    : TypeOfExprType(E), Context(Context) { }
2148
2149  bool isSugared() const { return false; }
2150  QualType desugar() const { return QualType(this, 0); }
2151
2152  void Profile(llvm::FoldingSetNodeID &ID) {
2153    Profile(ID, Context, getUnderlyingExpr());
2154  }
2155
2156  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2157                      Expr *E);
2158};
2159
2160/// TypeOfType (GCC extension).
2161class TypeOfType : public Type {
2162  QualType TOType;
2163  TypeOfType(QualType T, QualType can)
2164    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
2165    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2166  }
2167  friend class ASTContext;  // ASTContext creates these.
2168public:
2169  QualType getUnderlyingType() const { return TOType; }
2170
2171  /// \brief Remove a single level of sugar.
2172  QualType desugar() const { return getUnderlyingType(); }
2173
2174  /// \brief Returns whether this type directly provides sugar.
2175  bool isSugared() const { return true; }
2176
2177  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2178  static bool classof(const TypeOfType *) { return true; }
2179};
2180
2181/// DecltypeType (C++0x)
2182class DecltypeType : public Type {
2183  Expr *E;
2184
2185  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2186  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2187  // from it.
2188  QualType UnderlyingType;
2189
2190protected:
2191  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2192  friend class ASTContext;  // ASTContext creates these.
2193public:
2194  Expr *getUnderlyingExpr() const { return E; }
2195  QualType getUnderlyingType() const { return UnderlyingType; }
2196
2197  /// \brief Remove a single level of sugar.
2198  QualType desugar() const { return getUnderlyingType(); }
2199
2200  /// \brief Returns whether this type directly provides sugar.
2201  bool isSugared() const { return !isDependentType(); }
2202
2203  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2204  static bool classof(const DecltypeType *) { return true; }
2205};
2206
2207/// \brief Internal representation of canonical, dependent
2208/// decltype(expr) types.
2209///
2210/// This class is used internally by the ASTContext to manage
2211/// canonical, dependent types, only. Clients will only see instances
2212/// of this class via DecltypeType nodes.
2213class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2214  ASTContext &Context;
2215
2216public:
2217  DependentDecltypeType(ASTContext &Context, Expr *E);
2218
2219  bool isSugared() const { return false; }
2220  QualType desugar() const { return QualType(this, 0); }
2221
2222  void Profile(llvm::FoldingSetNodeID &ID) {
2223    Profile(ID, Context, getUnderlyingExpr());
2224  }
2225
2226  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2227                      Expr *E);
2228};
2229
2230class TagType : public Type {
2231  /// Stores the TagDecl associated with this type. The decl will
2232  /// point to the TagDecl that actually defines the entity (or is a
2233  /// definition in progress), if there is such a definition. The
2234  /// single-bit value will be non-zero when this tag is in the
2235  /// process of being defined.
2236  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
2237  friend class ASTContext;
2238  friend class TagDecl;
2239
2240protected:
2241  TagType(TypeClass TC, const TagDecl *D, QualType can);
2242
2243  virtual Linkage getLinkageImpl() const;
2244
2245public:
2246  TagDecl *getDecl() const { return decl.getPointer(); }
2247
2248  /// @brief Determines whether this type is in the process of being
2249  /// defined.
2250  bool isBeingDefined() const { return decl.getInt(); }
2251  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
2252
2253  static bool classof(const Type *T) {
2254    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2255  }
2256  static bool classof(const TagType *) { return true; }
2257  static bool classof(const RecordType *) { return true; }
2258  static bool classof(const EnumType *) { return true; }
2259};
2260
2261/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2262/// to detect TagType objects of structs/unions/classes.
2263class RecordType : public TagType {
2264protected:
2265  explicit RecordType(const RecordDecl *D)
2266    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2267  explicit RecordType(TypeClass TC, RecordDecl *D)
2268    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2269  friend class ASTContext;   // ASTContext creates these.
2270public:
2271
2272  RecordDecl *getDecl() const {
2273    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2274  }
2275
2276  // FIXME: This predicate is a helper to QualType/Type. It needs to
2277  // recursively check all fields for const-ness. If any field is declared
2278  // const, it needs to return false.
2279  bool hasConstFields() const { return false; }
2280
2281  // FIXME: RecordType needs to check when it is created that all fields are in
2282  // the same address space, and return that.
2283  unsigned getAddressSpace() const { return 0; }
2284
2285  bool isSugared() const { return false; }
2286  QualType desugar() const { return QualType(this, 0); }
2287
2288  static bool classof(const TagType *T);
2289  static bool classof(const Type *T) {
2290    return isa<TagType>(T) && classof(cast<TagType>(T));
2291  }
2292  static bool classof(const RecordType *) { return true; }
2293};
2294
2295/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2296/// to detect TagType objects of enums.
2297class EnumType : public TagType {
2298  explicit EnumType(const EnumDecl *D)
2299    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2300  friend class ASTContext;   // ASTContext creates these.
2301public:
2302
2303  EnumDecl *getDecl() const {
2304    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2305  }
2306
2307  bool isSugared() const { return false; }
2308  QualType desugar() const { return QualType(this, 0); }
2309
2310  static bool classof(const TagType *T);
2311  static bool classof(const Type *T) {
2312    return isa<TagType>(T) && classof(cast<TagType>(T));
2313  }
2314  static bool classof(const EnumType *) { return true; }
2315};
2316
2317class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2318  unsigned Depth : 15;
2319  unsigned Index : 16;
2320  unsigned ParameterPack : 1;
2321  IdentifierInfo *Name;
2322
2323  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2324                       QualType Canon)
2325    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2326      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2327
2328  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2329    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2330      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2331
2332  friend class ASTContext;  // ASTContext creates these
2333
2334public:
2335  unsigned getDepth() const { return Depth; }
2336  unsigned getIndex() const { return Index; }
2337  bool isParameterPack() const { return ParameterPack; }
2338  IdentifierInfo *getName() const { return Name; }
2339
2340  bool isSugared() const { return false; }
2341  QualType desugar() const { return QualType(this, 0); }
2342
2343  void Profile(llvm::FoldingSetNodeID &ID) {
2344    Profile(ID, Depth, Index, ParameterPack, Name);
2345  }
2346
2347  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2348                      unsigned Index, bool ParameterPack,
2349                      IdentifierInfo *Name) {
2350    ID.AddInteger(Depth);
2351    ID.AddInteger(Index);
2352    ID.AddBoolean(ParameterPack);
2353    ID.AddPointer(Name);
2354  }
2355
2356  static bool classof(const Type *T) {
2357    return T->getTypeClass() == TemplateTypeParm;
2358  }
2359  static bool classof(const TemplateTypeParmType *T) { return true; }
2360};
2361
2362/// \brief Represents the result of substituting a type for a template
2363/// type parameter.
2364///
2365/// Within an instantiated template, all template type parameters have
2366/// been replaced with these.  They are used solely to record that a
2367/// type was originally written as a template type parameter;
2368/// therefore they are never canonical.
2369class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2370  // The original type parameter.
2371  const TemplateTypeParmType *Replaced;
2372
2373  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2374    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType()),
2375      Replaced(Param) { }
2376
2377  friend class ASTContext;
2378
2379public:
2380  IdentifierInfo *getName() const { return Replaced->getName(); }
2381
2382  /// Gets the template parameter that was substituted for.
2383  const TemplateTypeParmType *getReplacedParameter() const {
2384    return Replaced;
2385  }
2386
2387  /// Gets the type that was substituted for the template
2388  /// parameter.
2389  QualType getReplacementType() const {
2390    return getCanonicalTypeInternal();
2391  }
2392
2393  bool isSugared() const { return true; }
2394  QualType desugar() const { return getReplacementType(); }
2395
2396  void Profile(llvm::FoldingSetNodeID &ID) {
2397    Profile(ID, getReplacedParameter(), getReplacementType());
2398  }
2399  static void Profile(llvm::FoldingSetNodeID &ID,
2400                      const TemplateTypeParmType *Replaced,
2401                      QualType Replacement) {
2402    ID.AddPointer(Replaced);
2403    ID.AddPointer(Replacement.getAsOpaquePtr());
2404  }
2405
2406  static bool classof(const Type *T) {
2407    return T->getTypeClass() == SubstTemplateTypeParm;
2408  }
2409  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2410};
2411
2412/// \brief Represents the type of a template specialization as written
2413/// in the source code.
2414///
2415/// Template specialization types represent the syntactic form of a
2416/// template-id that refers to a type, e.g., @c vector<int>. Some
2417/// template specialization types are syntactic sugar, whose canonical
2418/// type will point to some other type node that represents the
2419/// instantiation or class template specialization. For example, a
2420/// class template specialization type of @c vector<int> will refer to
2421/// a tag type for the instantiation
2422/// @c std::vector<int, std::allocator<int>>.
2423///
2424/// Other template specialization types, for which the template name
2425/// is dependent, may be canonical types. These types are always
2426/// dependent.
2427class TemplateSpecializationType
2428  : public Type, public llvm::FoldingSetNode {
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(TemplateName T,
2437                             const TemplateArgument *Args,
2438                             unsigned NumArgs, QualType Canon);
2439
2440  virtual void Destroy(ASTContext& C);
2441
2442  friend class ASTContext;  // ASTContext creates these
2443
2444public:
2445  /// \brief Determine whether any of the given template arguments are
2446  /// dependent.
2447  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2448                                            unsigned NumArgs);
2449
2450  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2451                                            unsigned NumArgs);
2452
2453  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
2454
2455  /// \brief Print a template argument list, including the '<' and '>'
2456  /// enclosing the template arguments.
2457  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2458                                               unsigned NumArgs,
2459                                               const PrintingPolicy &Policy);
2460
2461  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2462                                               unsigned NumArgs,
2463                                               const PrintingPolicy &Policy);
2464
2465  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
2466                                               const PrintingPolicy &Policy);
2467
2468  /// True if this template specialization type matches a current
2469  /// instantiation in the context in which it is found.
2470  bool isCurrentInstantiation() const {
2471    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
2472  }
2473
2474  typedef const TemplateArgument * iterator;
2475
2476  iterator begin() const { return getArgs(); }
2477  iterator end() const; // defined inline in TemplateBase.h
2478
2479  /// \brief Retrieve the name of the template that we are specializing.
2480  TemplateName getTemplateName() const { return Template; }
2481
2482  /// \brief Retrieve the template arguments.
2483  const TemplateArgument *getArgs() const {
2484    return reinterpret_cast<const TemplateArgument *>(this + 1);
2485  }
2486
2487  /// \brief Retrieve the number of template arguments.
2488  unsigned getNumArgs() const { return NumArgs; }
2489
2490  /// \brief Retrieve a specific template argument as a type.
2491  /// \precondition @c isArgType(Arg)
2492  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
2493
2494  bool isSugared() const {
2495    return !isDependentType() || isCurrentInstantiation();
2496  }
2497  QualType desugar() const { return getCanonicalTypeInternal(); }
2498
2499  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Ctx) {
2500    Profile(ID, Template, getArgs(), NumArgs, Ctx);
2501  }
2502
2503  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2504                      const TemplateArgument *Args,
2505                      unsigned NumArgs,
2506                      ASTContext &Context);
2507
2508  static bool classof(const Type *T) {
2509    return T->getTypeClass() == TemplateSpecialization;
2510  }
2511  static bool classof(const TemplateSpecializationType *T) { return true; }
2512};
2513
2514/// \brief The injected class name of a C++ class template or class
2515/// template partial specialization.  Used to record that a type was
2516/// spelled with a bare identifier rather than as a template-id; the
2517/// equivalent for non-templated classes is just RecordType.
2518///
2519/// Injected class name types are always dependent.  Template
2520/// instantiation turns these into RecordTypes.
2521///
2522/// Injected class name types are always canonical.  This works
2523/// because it is impossible to compare an injected class name type
2524/// with the corresponding non-injected template type, for the same
2525/// reason that it is impossible to directly compare template
2526/// parameters from different dependent contexts: injected class name
2527/// types can only occur within the scope of a particular templated
2528/// declaration, and within that scope every template specialization
2529/// will canonicalize to the injected class name (when appropriate
2530/// according to the rules of the language).
2531class InjectedClassNameType : public Type {
2532  CXXRecordDecl *Decl;
2533
2534  /// The template specialization which this type represents.
2535  /// For example, in
2536  ///   template <class T> class A { ... };
2537  /// this is A<T>, whereas in
2538  ///   template <class X, class Y> class A<B<X,Y> > { ... };
2539  /// this is A<B<X,Y> >.
2540  ///
2541  /// It is always unqualified, always a template specialization type,
2542  /// and always dependent.
2543  QualType InjectedType;
2544
2545  friend class ASTContext; // ASTContext creates these.
2546  friend class TagDecl; // TagDecl mutilates the Decl
2547  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
2548    : Type(InjectedClassName, QualType(), true),
2549      Decl(D), InjectedType(TST) {
2550    assert(isa<TemplateSpecializationType>(TST));
2551    assert(!TST.hasQualifiers());
2552    assert(TST->isDependentType());
2553  }
2554
2555public:
2556  QualType getInjectedSpecializationType() const { return InjectedType; }
2557  const TemplateSpecializationType *getInjectedTST() const {
2558    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
2559  }
2560
2561  CXXRecordDecl *getDecl() const { return Decl; }
2562
2563  bool isSugared() const { return false; }
2564  QualType desugar() const { return QualType(this, 0); }
2565
2566  static bool classof(const Type *T) {
2567    return T->getTypeClass() == InjectedClassName;
2568  }
2569  static bool classof(const InjectedClassNameType *T) { return true; }
2570};
2571
2572/// \brief The kind of a tag type.
2573enum TagTypeKind {
2574  /// \brief The "struct" keyword.
2575  TTK_Struct,
2576  /// \brief The "union" keyword.
2577  TTK_Union,
2578  /// \brief The "class" keyword.
2579  TTK_Class,
2580  /// \brief The "enum" keyword.
2581  TTK_Enum
2582};
2583
2584/// \brief The elaboration keyword that precedes a qualified type name or
2585/// introduces an elaborated-type-specifier.
2586enum ElaboratedTypeKeyword {
2587  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
2588  ETK_Struct,
2589  /// \brief The "union" keyword introduces the elaborated-type-specifier.
2590  ETK_Union,
2591  /// \brief The "class" keyword introduces the elaborated-type-specifier.
2592  ETK_Class,
2593  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
2594  ETK_Enum,
2595  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
2596  /// \c typename T::type.
2597  ETK_Typename,
2598  /// \brief No keyword precedes the qualified type name.
2599  ETK_None
2600};
2601
2602/// A helper class for Type nodes having an ElaboratedTypeKeyword.
2603/// The keyword in stored in the free bits of the base class.
2604/// Also provides a few static helpers for converting and printing
2605/// elaborated type keyword and tag type kind enumerations.
2606class TypeWithKeyword : public Type {
2607  /// Keyword - Encodes an ElaboratedTypeKeyword enumeration constant.
2608  unsigned Keyword : 3;
2609
2610protected:
2611  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
2612                  QualType Canonical, bool dependent)
2613    : Type(tc, Canonical, dependent), Keyword(Keyword) {}
2614
2615public:
2616  virtual ~TypeWithKeyword(); // pin vtable to Type.cpp
2617
2618  ElaboratedTypeKeyword getKeyword() const {
2619    return static_cast<ElaboratedTypeKeyword>(Keyword);
2620  }
2621
2622  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
2623  /// into an elaborated type keyword.
2624  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
2625
2626  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
2627  /// into a tag type kind.  It is an error to provide a type specifier
2628  /// which *isn't* a tag kind here.
2629  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
2630
2631  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
2632  /// elaborated type keyword.
2633  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
2634
2635  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
2636  // a TagTypeKind. It is an error to provide an elaborated type keyword
2637  /// which *isn't* a tag kind here.
2638  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
2639
2640  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
2641
2642  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
2643
2644  static const char *getTagTypeKindName(TagTypeKind Kind) {
2645    return getKeywordName(getKeywordForTagTypeKind(Kind));
2646  }
2647
2648  class CannotCastToThisType {};
2649  static CannotCastToThisType classof(const Type *);
2650};
2651
2652/// \brief Represents a type that was referred to using an elaborated type
2653/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
2654/// or both.
2655///
2656/// This type is used to keep track of a type name as written in the
2657/// source code, including tag keywords and any nested-name-specifiers.
2658/// The type itself is always "sugar", used to express what was written
2659/// in the source code but containing no additional semantic information.
2660class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
2661
2662  /// \brief The nested name specifier containing the qualifier.
2663  NestedNameSpecifier *NNS;
2664
2665  /// \brief The type that this qualified name refers to.
2666  QualType NamedType;
2667
2668  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2669                 QualType NamedType, QualType CanonType)
2670    : TypeWithKeyword(Keyword, Elaborated, CanonType,
2671                      NamedType->isDependentType()),
2672      NNS(NNS), NamedType(NamedType) {
2673    assert(!(Keyword == ETK_None && NNS == 0) &&
2674           "ElaboratedType cannot have elaborated type keyword "
2675           "and name qualifier both null.");
2676  }
2677
2678  friend class ASTContext;  // ASTContext creates these
2679
2680public:
2681  ~ElaboratedType();
2682
2683  /// \brief Retrieve the qualification on this type.
2684  NestedNameSpecifier *getQualifier() const { return NNS; }
2685
2686  /// \brief Retrieve the type named by the qualified-id.
2687  QualType getNamedType() const { return NamedType; }
2688
2689  /// \brief Remove a single level of sugar.
2690  QualType desugar() const { return getNamedType(); }
2691
2692  /// \brief Returns whether this type directly provides sugar.
2693  bool isSugared() const { return true; }
2694
2695  void Profile(llvm::FoldingSetNodeID &ID) {
2696    Profile(ID, getKeyword(), NNS, NamedType);
2697  }
2698
2699  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2700                      NestedNameSpecifier *NNS, QualType NamedType) {
2701    ID.AddInteger(Keyword);
2702    ID.AddPointer(NNS);
2703    NamedType.Profile(ID);
2704  }
2705
2706  static bool classof(const Type *T) {
2707    return T->getTypeClass() == Elaborated;
2708  }
2709  static bool classof(const ElaboratedType *T) { return true; }
2710};
2711
2712/// \brief Represents a qualified type name for which the type name is
2713/// dependent.
2714///
2715/// DependentNameType represents a class of dependent types that involve a
2716/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
2717/// name of a type. The DependentNameType may start with a "typename" (for a
2718/// typename-specifier), "class", "struct", "union", or "enum" (for a
2719/// dependent elaborated-type-specifier), or nothing (in contexts where we
2720/// know that we must be referring to a type, e.g., in a base class specifier).
2721class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
2722
2723  /// \brief The nested name specifier containing the qualifier.
2724  NestedNameSpecifier *NNS;
2725
2726  /// \brief The type that this typename specifier refers to.
2727  const IdentifierInfo *Name;
2728
2729  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2730                    const IdentifierInfo *Name, QualType CanonType)
2731    : TypeWithKeyword(Keyword, DependentName, CanonType, true),
2732      NNS(NNS), Name(Name) {
2733    assert(NNS->isDependent() &&
2734           "DependentNameType requires a dependent nested-name-specifier");
2735  }
2736
2737  friend class ASTContext;  // ASTContext creates these
2738
2739public:
2740  virtual ~DependentNameType();
2741
2742  /// \brief Retrieve the qualification on this type.
2743  NestedNameSpecifier *getQualifier() const { return NNS; }
2744
2745  /// \brief Retrieve the type named by the typename specifier as an
2746  /// identifier.
2747  ///
2748  /// This routine will return a non-NULL identifier pointer when the
2749  /// form of the original typename was terminated by an identifier,
2750  /// e.g., "typename T::type".
2751  const IdentifierInfo *getIdentifier() const {
2752    return Name;
2753  }
2754
2755  bool isSugared() const { return false; }
2756  QualType desugar() const { return QualType(this, 0); }
2757
2758  void Profile(llvm::FoldingSetNodeID &ID) {
2759    Profile(ID, getKeyword(), NNS, Name);
2760  }
2761
2762  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2763                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
2764    ID.AddInteger(Keyword);
2765    ID.AddPointer(NNS);
2766    ID.AddPointer(Name);
2767  }
2768
2769  static bool classof(const Type *T) {
2770    return T->getTypeClass() == DependentName;
2771  }
2772  static bool classof(const DependentNameType *T) { return true; }
2773};
2774
2775/// DependentTemplateSpecializationType - Represents a template
2776/// specialization type whose template cannot be resolved, e.g.
2777///   A<T>::template B<T>
2778class DependentTemplateSpecializationType :
2779  public TypeWithKeyword, public llvm::FoldingSetNode {
2780
2781  /// \brief The nested name specifier containing the qualifier.
2782  NestedNameSpecifier *NNS;
2783
2784  /// \brief The identifier of the template.
2785  const IdentifierInfo *Name;
2786
2787  /// \brief - The number of template arguments named in this class
2788  /// template specialization.
2789  unsigned NumArgs;
2790
2791  const TemplateArgument *getArgBuffer() const {
2792    return reinterpret_cast<const TemplateArgument*>(this+1);
2793  }
2794  TemplateArgument *getArgBuffer() {
2795    return reinterpret_cast<TemplateArgument*>(this+1);
2796  }
2797
2798  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
2799                                      NestedNameSpecifier *NNS,
2800                                      const IdentifierInfo *Name,
2801                                      unsigned NumArgs,
2802                                      const TemplateArgument *Args,
2803                                      QualType Canon);
2804
2805  virtual void Destroy(ASTContext& C);
2806
2807  friend class ASTContext;  // ASTContext creates these
2808
2809public:
2810  virtual ~DependentTemplateSpecializationType();
2811
2812  NestedNameSpecifier *getQualifier() const { return NNS; }
2813  const IdentifierInfo *getIdentifier() const { return Name; }
2814
2815  /// \brief Retrieve the template arguments.
2816  const TemplateArgument *getArgs() const {
2817    return getArgBuffer();
2818  }
2819
2820  /// \brief Retrieve the number of template arguments.
2821  unsigned getNumArgs() const { return NumArgs; }
2822
2823  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
2824
2825  typedef const TemplateArgument * iterator;
2826  iterator begin() const { return getArgs(); }
2827  iterator end() const; // inline in TemplateBase.h
2828
2829  bool isSugared() const { return false; }
2830  QualType desugar() const { return QualType(this, 0); }
2831
2832  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context) {
2833    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
2834  }
2835
2836  static void Profile(llvm::FoldingSetNodeID &ID,
2837                      ASTContext &Context,
2838                      ElaboratedTypeKeyword Keyword,
2839                      NestedNameSpecifier *Qualifier,
2840                      const IdentifierInfo *Name,
2841                      unsigned NumArgs,
2842                      const TemplateArgument *Args);
2843
2844  static bool classof(const Type *T) {
2845    return T->getTypeClass() == DependentTemplateSpecialization;
2846  }
2847  static bool classof(const DependentTemplateSpecializationType *T) {
2848    return true;
2849  }
2850};
2851
2852/// ObjCObjectType - Represents a class type in Objective C.
2853/// Every Objective C type is a combination of a base type and a
2854/// list of protocols.
2855///
2856/// Given the following declarations:
2857///   @class C;
2858///   @protocol P;
2859///
2860/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
2861/// with base C and no protocols.
2862///
2863/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
2864///
2865/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
2866/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
2867/// and no protocols.
2868///
2869/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
2870/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
2871/// this should get its own sugar class to better represent the source.
2872class ObjCObjectType : public Type {
2873  // Pad the bit count up so that NumProtocols is 2-byte aligned
2874  unsigned : BitsRemainingInType - 16;
2875
2876  /// \brief The number of protocols stored after the
2877  /// ObjCObjectPointerType node.
2878  ///
2879  /// These protocols are those written directly on the type.  If
2880  /// protocol qualifiers ever become additive, the iterators will
2881  /// get kindof complicated.
2882  ///
2883  /// In the canonical object type, these are sorted alphabetically
2884  /// and uniqued.
2885  unsigned NumProtocols : 16;
2886
2887  /// Either a BuiltinType or an InterfaceType or sugar for either.
2888  QualType BaseType;
2889
2890  ObjCProtocolDecl * const *getProtocolStorage() const {
2891    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
2892  }
2893
2894  ObjCProtocolDecl **getProtocolStorage();
2895
2896protected:
2897  ObjCObjectType(QualType Canonical, QualType Base,
2898                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
2899
2900  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
2901  ObjCObjectType(enum Nonce_ObjCInterface)
2902    : Type(ObjCInterface, QualType(), false),
2903      NumProtocols(0),
2904      BaseType(QualType(this_(), 0)) {}
2905
2906protected:
2907  Linkage getLinkageImpl() const; // key function
2908
2909public:
2910  /// getBaseType - Gets the base type of this object type.  This is
2911  /// always (possibly sugar for) one of:
2912  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
2913  ///    user, which is a typedef for an ObjCPointerType)
2914  ///  - the 'Class' builtin type (same caveat)
2915  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
2916  QualType getBaseType() const { return BaseType; }
2917
2918  bool isObjCId() const {
2919    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
2920  }
2921  bool isObjCClass() const {
2922    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
2923  }
2924  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
2925  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
2926  bool isObjCUnqualifiedIdOrClass() const {
2927    if (!qual_empty()) return false;
2928    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
2929      return T->getKind() == BuiltinType::ObjCId ||
2930             T->getKind() == BuiltinType::ObjCClass;
2931    return false;
2932  }
2933  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
2934  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
2935
2936  /// Gets the interface declaration for this object type, if the base type
2937  /// really is an interface.
2938  ObjCInterfaceDecl *getInterface() const;
2939
2940  typedef ObjCProtocolDecl * const *qual_iterator;
2941
2942  qual_iterator qual_begin() const { return getProtocolStorage(); }
2943  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
2944
2945  bool qual_empty() const { return getNumProtocols() == 0; }
2946
2947  /// getNumProtocols - Return the number of qualifying protocols in this
2948  /// interface type, or 0 if there are none.
2949  unsigned getNumProtocols() const { return NumProtocols; }
2950
2951  /// \brief Fetch a protocol by index.
2952  ObjCProtocolDecl *getProtocol(unsigned I) const {
2953    assert(I < getNumProtocols() && "Out-of-range protocol access");
2954    return qual_begin()[I];
2955  }
2956
2957  bool isSugared() const { return false; }
2958  QualType desugar() const { return QualType(this, 0); }
2959
2960  static bool classof(const Type *T) {
2961    return T->getTypeClass() == ObjCObject ||
2962           T->getTypeClass() == ObjCInterface;
2963  }
2964  static bool classof(const ObjCObjectType *) { return true; }
2965};
2966
2967/// ObjCObjectTypeImpl - A class providing a concrete implementation
2968/// of ObjCObjectType, so as to not increase the footprint of
2969/// ObjCInterfaceType.  Code outside of ASTContext and the core type
2970/// system should not reference this type.
2971class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
2972  friend class ASTContext;
2973
2974  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
2975  // will need to be modified.
2976
2977  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
2978                     ObjCProtocolDecl * const *Protocols,
2979                     unsigned NumProtocols)
2980    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
2981
2982public:
2983  void Destroy(ASTContext& C); // key function
2984
2985  void Profile(llvm::FoldingSetNodeID &ID);
2986  static void Profile(llvm::FoldingSetNodeID &ID,
2987                      QualType Base,
2988                      ObjCProtocolDecl *const *protocols,
2989                      unsigned NumProtocols);
2990};
2991
2992inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
2993  return reinterpret_cast<ObjCProtocolDecl**>(
2994            static_cast<ObjCObjectTypeImpl*>(this) + 1);
2995}
2996
2997/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2998/// object oriented design.  They basically correspond to C++ classes.  There
2999/// are two kinds of interface types, normal interfaces like "NSString" and
3000/// qualified interfaces, which are qualified with a protocol list like
3001/// "NSString<NSCopyable, NSAmazing>".
3002///
3003/// ObjCInterfaceType guarantees the following properties when considered
3004/// as a subtype of its superclass, ObjCObjectType:
3005///   - There are no protocol qualifiers.  To reinforce this, code which
3006///     tries to invoke the protocol methods via an ObjCInterfaceType will
3007///     fail to compile.
3008///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3009///     T->getBaseType() == QualType(T, 0).
3010class ObjCInterfaceType : public ObjCObjectType {
3011  ObjCInterfaceDecl *Decl;
3012
3013  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3014    : ObjCObjectType(Nonce_ObjCInterface),
3015      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3016  friend class ASTContext;  // ASTContext creates these.
3017public:
3018  void Destroy(ASTContext& C); // key function
3019
3020  /// getDecl - Get the declaration of this interface.
3021  ObjCInterfaceDecl *getDecl() const { return Decl; }
3022
3023  bool isSugared() const { return false; }
3024  QualType desugar() const { return QualType(this, 0); }
3025
3026  static bool classof(const Type *T) {
3027    return T->getTypeClass() == ObjCInterface;
3028  }
3029  static bool classof(const ObjCInterfaceType *) { return true; }
3030
3031  // Nonsense to "hide" certain members of ObjCObjectType within this
3032  // class.  People asking for protocols on an ObjCInterfaceType are
3033  // not going to get what they want: ObjCInterfaceTypes are
3034  // guaranteed to have no protocols.
3035  enum {
3036    qual_iterator,
3037    qual_begin,
3038    qual_end,
3039    getNumProtocols,
3040    getProtocol
3041  };
3042};
3043
3044inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3045  if (const ObjCInterfaceType *T =
3046        getBaseType()->getAs<ObjCInterfaceType>())
3047    return T->getDecl();
3048  return 0;
3049}
3050
3051/// ObjCObjectPointerType - Used to represent a pointer to an
3052/// Objective C object.  These are constructed from pointer
3053/// declarators when the pointee type is an ObjCObjectType (or sugar
3054/// for one).  In addition, the 'id' and 'Class' types are typedefs
3055/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3056/// are translated into these.
3057///
3058/// Pointers to pointers to Objective C objects are still PointerTypes;
3059/// only the first level of pointer gets it own type implementation.
3060class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3061  QualType PointeeType;
3062
3063  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3064    : Type(ObjCObjectPointer, Canonical, false),
3065      PointeeType(Pointee) {}
3066  friend class ASTContext;  // ASTContext creates these.
3067
3068protected:
3069  virtual Linkage getLinkageImpl() const;
3070
3071public:
3072  void Destroy(ASTContext& C);
3073
3074  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3075  /// The result will always be an ObjCObjectType or sugar thereof.
3076  QualType getPointeeType() const { return PointeeType; }
3077
3078  /// getObjCObjectType - Gets the type pointed to by this ObjC
3079  /// pointer.  This method always returns non-null.
3080  ///
3081  /// This method is equivalent to getPointeeType() except that
3082  /// it discards any typedefs (or other sugar) between this
3083  /// type and the "outermost" object type.  So for:
3084  ///   @class A; @protocol P; @protocol Q;
3085  ///   typedef A<P> AP;
3086  ///   typedef A A1;
3087  ///   typedef A1<P> A1P;
3088  ///   typedef A1P<Q> A1PQ;
3089  /// For 'A*', getObjectType() will return 'A'.
3090  /// For 'A<P>*', getObjectType() will return 'A<P>'.
3091  /// For 'AP*', getObjectType() will return 'A<P>'.
3092  /// For 'A1*', getObjectType() will return 'A'.
3093  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
3094  /// For 'A1P*', getObjectType() will return 'A1<P>'.
3095  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
3096  ///   adding protocols to a protocol-qualified base discards the
3097  ///   old qualifiers (for now).  But if it didn't, getObjectType()
3098  ///   would return 'A1P<Q>' (and we'd have to make iterating over
3099  ///   qualifiers more complicated).
3100  const ObjCObjectType *getObjectType() const {
3101    return PointeeType->getAs<ObjCObjectType>();
3102  }
3103
3104  /// getInterfaceType - If this pointer points to an Objective C
3105  /// @interface type, gets the type for that interface.  Any protocol
3106  /// qualifiers on the interface are ignored.
3107  ///
3108  /// \return null if the base type for this pointer is 'id' or 'Class'
3109  const ObjCInterfaceType *getInterfaceType() const {
3110    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
3111  }
3112
3113  /// getInterfaceDecl - If this pointer points to an Objective @interface
3114  /// type, gets the declaration for that interface.
3115  ///
3116  /// \return null if the base type for this pointer is 'id' or 'Class'
3117  ObjCInterfaceDecl *getInterfaceDecl() const {
3118    return getObjectType()->getInterface();
3119  }
3120
3121  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
3122  /// its object type is the primitive 'id' type with no protocols.
3123  bool isObjCIdType() const {
3124    return getObjectType()->isObjCUnqualifiedId();
3125  }
3126
3127  /// isObjCClassType - True if this is equivalent to the 'Class' type,
3128  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
3129  bool isObjCClassType() const {
3130    return getObjectType()->isObjCUnqualifiedClass();
3131  }
3132
3133  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
3134  /// non-empty set of protocols.
3135  bool isObjCQualifiedIdType() const {
3136    return getObjectType()->isObjCQualifiedId();
3137  }
3138
3139  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
3140  /// some non-empty set of protocols.
3141  bool isObjCQualifiedClassType() const {
3142    return getObjectType()->isObjCQualifiedClass();
3143  }
3144
3145  /// An iterator over the qualifiers on the object type.  Provided
3146  /// for convenience.  This will always iterate over the full set of
3147  /// protocols on a type, not just those provided directly.
3148  typedef ObjCObjectType::qual_iterator qual_iterator;
3149
3150  qual_iterator qual_begin() const {
3151    return getObjectType()->qual_begin();
3152  }
3153  qual_iterator qual_end() const {
3154    return getObjectType()->qual_end();
3155  }
3156  bool qual_empty() const { return getObjectType()->qual_empty(); }
3157
3158  /// getNumProtocols - Return the number of qualifying protocols on
3159  /// the object type.
3160  unsigned getNumProtocols() const {
3161    return getObjectType()->getNumProtocols();
3162  }
3163
3164  /// \brief Retrieve a qualifying protocol by index on the object
3165  /// type.
3166  ObjCProtocolDecl *getProtocol(unsigned I) const {
3167    return getObjectType()->getProtocol(I);
3168  }
3169
3170  bool isSugared() const { return false; }
3171  QualType desugar() const { return QualType(this, 0); }
3172
3173  void Profile(llvm::FoldingSetNodeID &ID) {
3174    Profile(ID, getPointeeType());
3175  }
3176  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
3177    ID.AddPointer(T.getAsOpaquePtr());
3178  }
3179  static bool classof(const Type *T) {
3180    return T->getTypeClass() == ObjCObjectPointer;
3181  }
3182  static bool classof(const ObjCObjectPointerType *) { return true; }
3183};
3184
3185/// A qualifier set is used to build a set of qualifiers.
3186class QualifierCollector : public Qualifiers {
3187  ASTContext *Context;
3188
3189public:
3190  QualifierCollector(Qualifiers Qs = Qualifiers())
3191    : Qualifiers(Qs), Context(0) {}
3192  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
3193    : Qualifiers(Qs), Context(&Context) {}
3194
3195  void setContext(ASTContext &C) { Context = &C; }
3196
3197  /// Collect any qualifiers on the given type and return an
3198  /// unqualified type.
3199  const Type *strip(QualType QT) {
3200    addFastQualifiers(QT.getLocalFastQualifiers());
3201    if (QT.hasLocalNonFastQualifiers()) {
3202      const ExtQuals *EQ = QT.getExtQualsUnsafe();
3203      Context = &EQ->getContext();
3204      addQualifiers(EQ->getQualifiers());
3205      return EQ->getBaseType();
3206    }
3207    return QT.getTypePtrUnsafe();
3208  }
3209
3210  /// Apply the collected qualifiers to the given type.
3211  QualType apply(QualType QT) const;
3212
3213  /// Apply the collected qualifiers to the given type.
3214  QualType apply(const Type* T) const;
3215
3216};
3217
3218
3219// Inline function definitions.
3220
3221inline bool QualType::isCanonical() const {
3222  const Type *T = getTypePtr();
3223  if (hasLocalQualifiers())
3224    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
3225  return T->isCanonicalUnqualified();
3226}
3227
3228inline bool QualType::isCanonicalAsParam() const {
3229  if (hasLocalQualifiers()) return false;
3230  const Type *T = getTypePtr();
3231  return T->isCanonicalUnqualified() &&
3232           !isa<FunctionType>(T) && !isa<ArrayType>(T);
3233}
3234
3235inline bool QualType::isConstQualified() const {
3236  return isLocalConstQualified() ||
3237              getTypePtr()->getCanonicalTypeInternal().isLocalConstQualified();
3238}
3239
3240inline bool QualType::isRestrictQualified() const {
3241  return isLocalRestrictQualified() ||
3242            getTypePtr()->getCanonicalTypeInternal().isLocalRestrictQualified();
3243}
3244
3245
3246inline bool QualType::isVolatileQualified() const {
3247  return isLocalVolatileQualified() ||
3248  getTypePtr()->getCanonicalTypeInternal().isLocalVolatileQualified();
3249}
3250
3251inline bool QualType::hasQualifiers() const {
3252  return hasLocalQualifiers() ||
3253                  getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers();
3254}
3255
3256inline Qualifiers QualType::getQualifiers() const {
3257  Qualifiers Quals = getLocalQualifiers();
3258  Quals.addQualifiers(
3259                 getTypePtr()->getCanonicalTypeInternal().getLocalQualifiers());
3260  return Quals;
3261}
3262
3263inline unsigned QualType::getCVRQualifiers() const {
3264  return getLocalCVRQualifiers() |
3265              getTypePtr()->getCanonicalTypeInternal().getLocalCVRQualifiers();
3266}
3267
3268/// getCVRQualifiersThroughArrayTypes - If there are CVR qualifiers for this
3269/// type, returns them. Otherwise, if this is an array type, recurses
3270/// on the element type until some qualifiers have been found or a non-array
3271/// type reached.
3272inline unsigned QualType::getCVRQualifiersThroughArrayTypes() const {
3273  if (unsigned Quals = getCVRQualifiers())
3274    return Quals;
3275  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3276  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3277    return AT->getElementType().getCVRQualifiersThroughArrayTypes();
3278  return 0;
3279}
3280
3281inline void QualType::removeConst() {
3282  removeFastQualifiers(Qualifiers::Const);
3283}
3284
3285inline void QualType::removeRestrict() {
3286  removeFastQualifiers(Qualifiers::Restrict);
3287}
3288
3289inline void QualType::removeVolatile() {
3290  QualifierCollector Qc;
3291  const Type *Ty = Qc.strip(*this);
3292  if (Qc.hasVolatile()) {
3293    Qc.removeVolatile();
3294    *this = Qc.apply(Ty);
3295  }
3296}
3297
3298inline void QualType::removeCVRQualifiers(unsigned Mask) {
3299  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
3300
3301  // Fast path: we don't need to touch the slow qualifiers.
3302  if (!(Mask & ~Qualifiers::FastMask)) {
3303    removeFastQualifiers(Mask);
3304    return;
3305  }
3306
3307  QualifierCollector Qc;
3308  const Type *Ty = Qc.strip(*this);
3309  Qc.removeCVRQualifiers(Mask);
3310  *this = Qc.apply(Ty);
3311}
3312
3313/// getAddressSpace - Return the address space of this type.
3314inline unsigned QualType::getAddressSpace() const {
3315  if (hasLocalNonFastQualifiers()) {
3316    const ExtQuals *EQ = getExtQualsUnsafe();
3317    if (EQ->hasAddressSpace())
3318      return EQ->getAddressSpace();
3319  }
3320
3321  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3322  if (CT.hasLocalNonFastQualifiers()) {
3323    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3324    if (EQ->hasAddressSpace())
3325      return EQ->getAddressSpace();
3326  }
3327
3328  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3329    return AT->getElementType().getAddressSpace();
3330  if (const RecordType *RT = dyn_cast<RecordType>(CT))
3331    return RT->getAddressSpace();
3332  return 0;
3333}
3334
3335/// getObjCGCAttr - Return the gc attribute of this type.
3336inline Qualifiers::GC QualType::getObjCGCAttr() const {
3337  if (hasLocalNonFastQualifiers()) {
3338    const ExtQuals *EQ = getExtQualsUnsafe();
3339    if (EQ->hasObjCGCAttr())
3340      return EQ->getObjCGCAttr();
3341  }
3342
3343  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3344  if (CT.hasLocalNonFastQualifiers()) {
3345    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3346    if (EQ->hasObjCGCAttr())
3347      return EQ->getObjCGCAttr();
3348  }
3349
3350  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3351      return AT->getElementType().getObjCGCAttr();
3352  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
3353    return PT->getPointeeType().getObjCGCAttr();
3354  // We most look at all pointer types, not just pointer to interface types.
3355  if (const PointerType *PT = CT->getAs<PointerType>())
3356    return PT->getPointeeType().getObjCGCAttr();
3357  return Qualifiers::GCNone;
3358}
3359
3360inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
3361  if (const PointerType *PT = t.getAs<PointerType>()) {
3362    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
3363      return FT->getExtInfo();
3364  } else if (const FunctionType *FT = t.getAs<FunctionType>())
3365    return FT->getExtInfo();
3366
3367  return FunctionType::ExtInfo();
3368}
3369
3370inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
3371  return getFunctionExtInfo(*t);
3372}
3373
3374/// isMoreQualifiedThan - Determine whether this type is more
3375/// qualified than the Other type. For example, "const volatile int"
3376/// is more qualified than "const int", "volatile int", and
3377/// "int". However, it is not more qualified than "const volatile
3378/// int".
3379inline bool QualType::isMoreQualifiedThan(QualType Other) const {
3380  // FIXME: work on arbitrary qualifiers
3381  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3382  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3383  if (getAddressSpace() != Other.getAddressSpace())
3384    return false;
3385  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
3386}
3387
3388/// isAtLeastAsQualifiedAs - Determine whether this type is at last
3389/// as qualified as the Other type. For example, "const volatile
3390/// int" is at least as qualified as "const int", "volatile int",
3391/// "int", and "const volatile int".
3392inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
3393  // FIXME: work on arbitrary qualifiers
3394  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3395  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3396  if (getAddressSpace() != Other.getAddressSpace())
3397    return false;
3398  return (MyQuals | OtherQuals) == MyQuals;
3399}
3400
3401/// getNonReferenceType - If Type is a reference type (e.g., const
3402/// int&), returns the type that the reference refers to ("const
3403/// int"). Otherwise, returns the type itself. This routine is used
3404/// throughout Sema to implement C++ 5p6:
3405///
3406///   If an expression initially has the type "reference to T" (8.3.2,
3407///   8.5.3), the type is adjusted to "T" prior to any further
3408///   analysis, the expression designates the object or function
3409///   denoted by the reference, and the expression is an lvalue.
3410inline QualType QualType::getNonReferenceType() const {
3411  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
3412    return RefType->getPointeeType();
3413  else
3414    return *this;
3415}
3416
3417inline bool Type::isFunctionType() const {
3418  return isa<FunctionType>(CanonicalType);
3419}
3420inline bool Type::isPointerType() const {
3421  return isa<PointerType>(CanonicalType);
3422}
3423inline bool Type::isAnyPointerType() const {
3424  return isPointerType() || isObjCObjectPointerType();
3425}
3426inline bool Type::isBlockPointerType() const {
3427  return isa<BlockPointerType>(CanonicalType);
3428}
3429inline bool Type::isReferenceType() const {
3430  return isa<ReferenceType>(CanonicalType);
3431}
3432inline bool Type::isLValueReferenceType() const {
3433  return isa<LValueReferenceType>(CanonicalType);
3434}
3435inline bool Type::isRValueReferenceType() const {
3436  return isa<RValueReferenceType>(CanonicalType);
3437}
3438inline bool Type::isFunctionPointerType() const {
3439  if (const PointerType* T = getAs<PointerType>())
3440    return T->getPointeeType()->isFunctionType();
3441  else
3442    return false;
3443}
3444inline bool Type::isMemberPointerType() const {
3445  return isa<MemberPointerType>(CanonicalType);
3446}
3447inline bool Type::isMemberFunctionPointerType() const {
3448  if (const MemberPointerType* T = getAs<MemberPointerType>())
3449    return T->getPointeeType()->isFunctionType();
3450  else
3451    return false;
3452}
3453inline bool Type::isArrayType() const {
3454  return isa<ArrayType>(CanonicalType);
3455}
3456inline bool Type::isConstantArrayType() const {
3457  return isa<ConstantArrayType>(CanonicalType);
3458}
3459inline bool Type::isIncompleteArrayType() const {
3460  return isa<IncompleteArrayType>(CanonicalType);
3461}
3462inline bool Type::isVariableArrayType() const {
3463  return isa<VariableArrayType>(CanonicalType);
3464}
3465inline bool Type::isDependentSizedArrayType() const {
3466  return isa<DependentSizedArrayType>(CanonicalType);
3467}
3468inline bool Type::isRecordType() const {
3469  return isa<RecordType>(CanonicalType);
3470}
3471inline bool Type::isAnyComplexType() const {
3472  return isa<ComplexType>(CanonicalType);
3473}
3474inline bool Type::isVectorType() const {
3475  return isa<VectorType>(CanonicalType);
3476}
3477inline bool Type::isExtVectorType() const {
3478  return isa<ExtVectorType>(CanonicalType);
3479}
3480inline bool Type::isObjCObjectPointerType() const {
3481  return isa<ObjCObjectPointerType>(CanonicalType);
3482}
3483inline bool Type::isObjCObjectType() const {
3484  return isa<ObjCObjectType>(CanonicalType);
3485}
3486inline bool Type::isObjCQualifiedIdType() const {
3487  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3488    return OPT->isObjCQualifiedIdType();
3489  return false;
3490}
3491inline bool Type::isObjCQualifiedClassType() const {
3492  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3493    return OPT->isObjCQualifiedClassType();
3494  return false;
3495}
3496inline bool Type::isObjCIdType() const {
3497  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3498    return OPT->isObjCIdType();
3499  return false;
3500}
3501inline bool Type::isObjCClassType() const {
3502  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3503    return OPT->isObjCClassType();
3504  return false;
3505}
3506inline bool Type::isObjCSelType() const {
3507  if (const PointerType *OPT = getAs<PointerType>())
3508    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
3509  return false;
3510}
3511inline bool Type::isObjCBuiltinType() const {
3512  return isObjCIdType() || isObjCClassType() || isObjCSelType();
3513}
3514inline bool Type::isTemplateTypeParmType() const {
3515  return isa<TemplateTypeParmType>(CanonicalType);
3516}
3517
3518inline bool Type::isBuiltinType() const {
3519  return getAs<BuiltinType>();
3520}
3521
3522inline bool Type::isSpecificBuiltinType(unsigned K) const {
3523  if (const BuiltinType *BT = getAs<BuiltinType>())
3524    if (BT->getKind() == (BuiltinType::Kind) K)
3525      return true;
3526  return false;
3527}
3528
3529/// \brief Determines whether this is a type for which one can define
3530/// an overloaded operator.
3531inline bool Type::isOverloadableType() const {
3532  return isDependentType() || isRecordType() || isEnumeralType();
3533}
3534
3535inline bool Type::hasPointerRepresentation() const {
3536  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
3537          isObjCObjectPointerType() || isNullPtrType());
3538}
3539
3540inline bool Type::hasObjCPointerRepresentation() const {
3541  return isObjCObjectPointerType();
3542}
3543
3544/// Insertion operator for diagnostics.  This allows sending QualType's into a
3545/// diagnostic with <<.
3546inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3547                                           QualType T) {
3548  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3549                  Diagnostic::ak_qualtype);
3550  return DB;
3551}
3552
3553/// Insertion operator for partial diagnostics.  This allows sending QualType's
3554/// into a diagnostic with <<.
3555inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3556                                           QualType T) {
3557  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3558                  Diagnostic::ak_qualtype);
3559  return PD;
3560}
3561
3562// Helper class template that is used by Type::getAs to ensure that one does
3563// not try to look through a qualified type to get to an array type.
3564template<typename T,
3565         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
3566                             llvm::is_base_of<ArrayType, T>::value)>
3567struct ArrayType_cannot_be_used_with_getAs { };
3568
3569template<typename T>
3570struct ArrayType_cannot_be_used_with_getAs<T, true>;
3571
3572/// Member-template getAs<specific type>'.
3573template <typename T> const T *Type::getAs() const {
3574  ArrayType_cannot_be_used_with_getAs<T> at;
3575  (void)at;
3576
3577  // If this is directly a T type, return it.
3578  if (const T *Ty = dyn_cast<T>(this))
3579    return Ty;
3580
3581  // If the canonical form of this type isn't the right kind, reject it.
3582  if (!isa<T>(CanonicalType))
3583    return 0;
3584
3585  // If this is a typedef for the type, strip the typedef off without
3586  // losing all typedef information.
3587  return cast<T>(getUnqualifiedDesugaredType());
3588}
3589
3590}  // end namespace clang
3591
3592#endif
3593