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