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