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