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