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