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