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