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