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