Type.h revision d07cc36c71558b62889691184dd04655a33fd12a
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/ExceptionSpecificationType.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/Linkage.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/Visibility.h"
23#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/TemplateName.h"
25#include "llvm/Support/type_traits.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/ADT/APSInt.h"
28#include "llvm/ADT/FoldingSet.h"
29#include "llvm/ADT/Optional.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32#include "clang/Basic/LLVM.h"
33
34namespace clang {
35  enum {
36    TypeAlignmentInBits = 4,
37    TypeAlignment = 1 << TypeAlignmentInBits
38  };
39  class Type;
40  class ExtQuals;
41  class QualType;
42}
43
44namespace llvm {
45  template <typename T>
46  class PointerLikeTypeTraits;
47  template<>
48  class PointerLikeTypeTraits< ::clang::Type*> {
49  public:
50    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
51    static inline ::clang::Type *getFromVoidPointer(void *P) {
52      return static_cast< ::clang::Type*>(P);
53    }
54    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
55  };
56  template<>
57  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
58  public:
59    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
60    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
61      return static_cast< ::clang::ExtQuals*>(P);
62    }
63    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
64  };
65
66  template <>
67  struct isPodLike<clang::QualType> { static const bool value = true; };
68}
69
70namespace clang {
71  class ASTContext;
72  class TypedefNameDecl;
73  class TemplateDecl;
74  class TemplateTypeParmDecl;
75  class NonTypeTemplateParmDecl;
76  class TemplateTemplateParmDecl;
77  class TagDecl;
78  class RecordDecl;
79  class CXXRecordDecl;
80  class EnumDecl;
81  class FieldDecl;
82  class ObjCInterfaceDecl;
83  class ObjCProtocolDecl;
84  class ObjCMethodDecl;
85  class UnresolvedUsingTypenameDecl;
86  class Expr;
87  class Stmt;
88  class SourceLocation;
89  class StmtIteratorBase;
90  class TemplateArgument;
91  class TemplateArgumentLoc;
92  class TemplateArgumentListInfo;
93  class ElaboratedType;
94  class ExtQuals;
95  class ExtQualsTypeCommonBase;
96  struct PrintingPolicy;
97
98  template <typename> class CanQual;
99  typedef CanQual<Type> CanQualType;
100
101  // Provide forward declarations for all of the *Type classes
102#define TYPE(Class, Base) class Class##Type;
103#include "clang/AST/TypeNodes.def"
104
105/// Qualifiers - The collection of all-type qualifiers we support.
106/// Clang supports five independent qualifiers:
107/// * C99: const, volatile, and restrict
108/// * Embedded C (TR18037): address spaces
109/// * Objective C: the GC attributes (none, weak, or strong)
110class Qualifiers {
111public:
112  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
113    Const    = 0x1,
114    Restrict = 0x2,
115    Volatile = 0x4,
116    CVRMask = Const | Volatile | Restrict
117  };
118
119  enum GC {
120    GCNone = 0,
121    Weak,
122    Strong
123  };
124
125  enum ObjCLifetime {
126    /// There is no lifetime qualification on this type.
127    OCL_None,
128
129    /// This object can be modified without requiring retains or
130    /// releases.
131    OCL_ExplicitNone,
132
133    /// Assigning into this object requires the old value to be
134    /// released and the new value to be retained.  The timing of the
135    /// release of the old value is inexact: it may be moved to
136    /// immediately after the last known point where the value is
137    /// live.
138    OCL_Strong,
139
140    /// Reading or writing from this object requires a barrier call.
141    OCL_Weak,
142
143    /// Assigning into this object requires a lifetime extension.
144    OCL_Autoreleasing
145  };
146
147  enum {
148    /// The maximum supported address space number.
149    /// 24 bits should be enough for anyone.
150    MaxAddressSpace = 0xffffffu,
151
152    /// The width of the "fast" qualifier mask.
153    FastWidth = 3,
154
155    /// The fast qualifier mask.
156    FastMask = (1 << FastWidth) - 1
157  };
158
159  Qualifiers() : Mask(0) {}
160
161  static Qualifiers fromFastMask(unsigned Mask) {
162    Qualifiers Qs;
163    Qs.addFastQualifiers(Mask);
164    return Qs;
165  }
166
167  static Qualifiers fromCVRMask(unsigned CVR) {
168    Qualifiers Qs;
169    Qs.addCVRQualifiers(CVR);
170    return Qs;
171  }
172
173  // Deserialize qualifiers from an opaque representation.
174  static Qualifiers fromOpaqueValue(unsigned opaque) {
175    Qualifiers Qs;
176    Qs.Mask = opaque;
177    return Qs;
178  }
179
180  // Serialize these qualifiers into an opaque representation.
181  unsigned getAsOpaqueValue() const {
182    return Mask;
183  }
184
185  bool hasConst() const { return Mask & Const; }
186  void setConst(bool flag) {
187    Mask = (Mask & ~Const) | (flag ? Const : 0);
188  }
189  void removeConst() { Mask &= ~Const; }
190  void addConst() { Mask |= Const; }
191
192  bool hasVolatile() const { return Mask & Volatile; }
193  void setVolatile(bool flag) {
194    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
195  }
196  void removeVolatile() { Mask &= ~Volatile; }
197  void addVolatile() { Mask |= Volatile; }
198
199  bool hasRestrict() const { return Mask & Restrict; }
200  void setRestrict(bool flag) {
201    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
202  }
203  void removeRestrict() { Mask &= ~Restrict; }
204  void addRestrict() { Mask |= Restrict; }
205
206  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
207  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
208  void setCVRQualifiers(unsigned mask) {
209    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
210    Mask = (Mask & ~CVRMask) | mask;
211  }
212  void removeCVRQualifiers(unsigned mask) {
213    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
214    Mask &= ~mask;
215  }
216  void removeCVRQualifiers() {
217    removeCVRQualifiers(CVRMask);
218  }
219  void addCVRQualifiers(unsigned mask) {
220    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
221    Mask |= mask;
222  }
223
224  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
225  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
226  void setObjCGCAttr(GC type) {
227    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
228  }
229  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
230  void addObjCGCAttr(GC type) {
231    assert(type);
232    setObjCGCAttr(type);
233  }
234  Qualifiers withoutObjCGCAttr() const {
235    Qualifiers qs = *this;
236    qs.removeObjCGCAttr();
237    return qs;
238  }
239  Qualifiers withoutObjCGLifetime() const {
240    Qualifiers qs = *this;
241    qs.removeObjCLifetime();
242    return qs;
243  }
244
245  bool hasObjCLifetime() const { return Mask & LifetimeMask; }
246  ObjCLifetime getObjCLifetime() const {
247    return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
248  }
249  void setObjCLifetime(ObjCLifetime type) {
250    Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
251  }
252  void removeObjCLifetime() { setObjCLifetime(OCL_None); }
253  void addObjCLifetime(ObjCLifetime type) {
254    assert(type);
255    setObjCLifetime(type);
256  }
257
258  /// True if the lifetime is neither None or ExplicitNone.
259  bool hasNonTrivialObjCLifetime() const {
260    ObjCLifetime lifetime = getObjCLifetime();
261    return (lifetime > OCL_ExplicitNone);
262  }
263
264  /// True if the lifetime is either strong or weak.
265  bool hasStrongOrWeakObjCLifetime() const {
266    ObjCLifetime lifetime = getObjCLifetime();
267    return (lifetime == OCL_Strong || lifetime == OCL_Weak);
268  }
269
270  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
271  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
272  void setAddressSpace(unsigned space) {
273    assert(space <= MaxAddressSpace);
274    Mask = (Mask & ~AddressSpaceMask)
275         | (((uint32_t) space) << AddressSpaceShift);
276  }
277  void removeAddressSpace() { setAddressSpace(0); }
278  void addAddressSpace(unsigned space) {
279    assert(space);
280    setAddressSpace(space);
281  }
282
283  // Fast qualifiers are those that can be allocated directly
284  // on a QualType object.
285  bool hasFastQualifiers() const { return getFastQualifiers(); }
286  unsigned getFastQualifiers() const { return Mask & FastMask; }
287  void setFastQualifiers(unsigned mask) {
288    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
289    Mask = (Mask & ~FastMask) | mask;
290  }
291  void removeFastQualifiers(unsigned mask) {
292    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
293    Mask &= ~mask;
294  }
295  void removeFastQualifiers() {
296    removeFastQualifiers(FastMask);
297  }
298  void addFastQualifiers(unsigned mask) {
299    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
300    Mask |= mask;
301  }
302
303  /// hasNonFastQualifiers - Return true if the set contains any
304  /// qualifiers which require an ExtQuals node to be allocated.
305  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
306  Qualifiers getNonFastQualifiers() const {
307    Qualifiers Quals = *this;
308    Quals.setFastQualifiers(0);
309    return Quals;
310  }
311
312  /// hasQualifiers - Return true if the set contains any qualifiers.
313  bool hasQualifiers() const { return Mask; }
314  bool empty() const { return !Mask; }
315
316  /// \brief Add the qualifiers from the given set to this set.
317  void addQualifiers(Qualifiers Q) {
318    // If the other set doesn't have any non-boolean qualifiers, just
319    // bit-or it in.
320    if (!(Q.Mask & ~CVRMask))
321      Mask |= Q.Mask;
322    else {
323      Mask |= (Q.Mask & CVRMask);
324      if (Q.hasAddressSpace())
325        addAddressSpace(Q.getAddressSpace());
326      if (Q.hasObjCGCAttr())
327        addObjCGCAttr(Q.getObjCGCAttr());
328      if (Q.hasObjCLifetime())
329        addObjCLifetime(Q.getObjCLifetime());
330    }
331  }
332
333  /// \brief Add the qualifiers from the given set to this set, given that
334  /// they don't conflict.
335  void addConsistentQualifiers(Qualifiers qs) {
336    assert(getAddressSpace() == qs.getAddressSpace() ||
337           !hasAddressSpace() || !qs.hasAddressSpace());
338    assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
339           !hasObjCGCAttr() || !qs.hasObjCGCAttr());
340    assert(getObjCLifetime() == qs.getObjCLifetime() ||
341           !hasObjCLifetime() || !qs.hasObjCLifetime());
342    Mask |= qs.Mask;
343  }
344
345  /// \brief Determines if these qualifiers compatibly include another set.
346  /// Generally this answers the question of whether an object with the other
347  /// qualifiers can be safely used as an object with these qualifiers.
348  bool compatiblyIncludes(Qualifiers other) const {
349    return
350      // Address spaces must match exactly.
351      getAddressSpace() == other.getAddressSpace() &&
352      // ObjC GC qualifiers can match, be added, or be removed, but can't be
353      // changed.
354      (getObjCGCAttr() == other.getObjCGCAttr() ||
355       !hasObjCGCAttr() || !other.hasObjCGCAttr()) &&
356      // ObjC lifetime qualifiers must match exactly.
357      getObjCLifetime() == other.getObjCLifetime() &&
358      // CVR qualifiers may subset.
359      (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
360  }
361
362  /// \brief Determines if these qualifiers compatibly include another set of
363  /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
364  ///
365  /// One set of Objective-C lifetime qualifiers compatibly includes the other
366  /// if the lifetime qualifiers match, or if both are non-__weak and the
367  /// including set also contains the 'const' qualifier.
368  bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
369    if (getObjCLifetime() == other.getObjCLifetime())
370      return true;
371
372    if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
373      return false;
374
375    return hasConst();
376  }
377
378  bool isSupersetOf(Qualifiers Other) const;
379
380  /// \brief Determine whether this set of qualifiers is a strict superset of
381  /// another set of qualifiers, not considering qualifier compatibility.
382  bool isStrictSupersetOf(Qualifiers Other) const;
383
384  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
385  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
386
387  operator bool() const { return hasQualifiers(); }
388
389  Qualifiers &operator+=(Qualifiers R) {
390    addQualifiers(R);
391    return *this;
392  }
393
394  // Union two qualifier sets.  If an enumerated qualifier appears
395  // in both sets, use the one from the right.
396  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
397    L += R;
398    return L;
399  }
400
401  Qualifiers &operator-=(Qualifiers R) {
402    Mask = Mask & ~(R.Mask);
403    return *this;
404  }
405
406  /// \brief Compute the difference between two qualifier sets.
407  friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
408    L -= R;
409    return L;
410  }
411
412  std::string getAsString() const;
413  std::string getAsString(const PrintingPolicy &Policy) const {
414    std::string Buffer;
415    getAsStringInternal(Buffer, Policy);
416    return Buffer;
417  }
418  void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
419
420  void Profile(llvm::FoldingSetNodeID &ID) const {
421    ID.AddInteger(Mask);
422  }
423
424private:
425
426  // bits:     |0 1 2|3 .. 4|5  ..  7|8   ...   31|
427  //           |C R V|GCAttr|Lifetime|AddressSpace|
428  uint32_t Mask;
429
430  static const uint32_t GCAttrMask = 0x18;
431  static const uint32_t GCAttrShift = 3;
432  static const uint32_t LifetimeMask = 0xE0;
433  static const uint32_t LifetimeShift = 5;
434  static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
435  static const uint32_t AddressSpaceShift = 8;
436};
437
438/// CallingConv - Specifies the calling convention that a function uses.
439enum CallingConv {
440  CC_Default,
441  CC_C,           // __attribute__((cdecl))
442  CC_X86StdCall,  // __attribute__((stdcall))
443  CC_X86FastCall, // __attribute__((fastcall))
444  CC_X86ThisCall, // __attribute__((thiscall))
445  CC_X86Pascal,   // __attribute__((pascal))
446  CC_AAPCS,       // __attribute__((pcs("aapcs")))
447  CC_AAPCS_VFP    // __attribute__((pcs("aapcs-vfp")))
448};
449
450typedef std::pair<const Type*, Qualifiers> SplitQualType;
451
452/// QualType - For efficiency, we don't store CV-qualified types as nodes on
453/// their own: instead each reference to a type stores the qualifiers.  This
454/// greatly reduces the number of nodes we need to allocate for types (for
455/// example we only need one for 'int', 'const int', 'volatile int',
456/// 'const volatile int', etc).
457///
458/// As an added efficiency bonus, instead of making this a pair, we
459/// just store the two bits we care about in the low bits of the
460/// pointer.  To handle the packing/unpacking, we make QualType be a
461/// simple wrapper class that acts like a smart pointer.  A third bit
462/// indicates whether there are extended qualifiers present, in which
463/// case the pointer points to a special structure.
464class QualType {
465  // Thankfully, these are efficiently composable.
466  llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
467                       Qualifiers::FastWidth> Value;
468
469  const ExtQuals *getExtQualsUnsafe() const {
470    return Value.getPointer().get<const ExtQuals*>();
471  }
472
473  const Type *getTypePtrUnsafe() const {
474    return Value.getPointer().get<const Type*>();
475  }
476
477  const ExtQualsTypeCommonBase *getCommonPtr() const {
478    assert(!isNull() && "Cannot retrieve a NULL type pointer");
479    uintptr_t CommonPtrVal
480      = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
481    CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
482    return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
483  }
484
485  friend class QualifierCollector;
486public:
487  QualType() {}
488
489  QualType(const Type *Ptr, unsigned Quals)
490    : Value(Ptr, Quals) {}
491  QualType(const ExtQuals *Ptr, unsigned Quals)
492    : Value(Ptr, Quals) {}
493
494  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
495  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
496
497  /// Retrieves a pointer to the underlying (unqualified) type.
498  /// This should really return a const Type, but it's not worth
499  /// changing all the users right now.
500  ///
501  /// This function requires that the type not be NULL. If the type might be
502  /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
503  const Type *getTypePtr() const;
504
505  const Type *getTypePtrOrNull() const;
506
507  /// Retrieves a pointer to the name of the base type.
508  const IdentifierInfo *getBaseTypeIdentifier() const;
509
510  /// Divides a QualType into its unqualified type and a set of local
511  /// qualifiers.
512  SplitQualType split() const;
513
514  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
515  static QualType getFromOpaquePtr(const void *Ptr) {
516    QualType T;
517    T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
518    return T;
519  }
520
521  const Type &operator*() const {
522    return *getTypePtr();
523  }
524
525  const Type *operator->() const {
526    return getTypePtr();
527  }
528
529  bool isCanonical() const;
530  bool isCanonicalAsParam() const;
531
532  /// isNull - Return true if this QualType doesn't point to a type yet.
533  bool isNull() const {
534    return Value.getPointer().isNull();
535  }
536
537  /// \brief Determine whether this particular QualType instance has the
538  /// "const" qualifier set, without looking through typedefs that may have
539  /// added "const" at a different level.
540  bool isLocalConstQualified() const {
541    return (getLocalFastQualifiers() & Qualifiers::Const);
542  }
543
544  /// \brief Determine whether this type is const-qualified.
545  bool isConstQualified() const;
546
547  /// \brief Determine whether this particular QualType instance has the
548  /// "restrict" qualifier set, without looking through typedefs that may have
549  /// added "restrict" at a different level.
550  bool isLocalRestrictQualified() const {
551    return (getLocalFastQualifiers() & Qualifiers::Restrict);
552  }
553
554  /// \brief Determine whether this type is restrict-qualified.
555  bool isRestrictQualified() const;
556
557  /// \brief Determine whether this particular QualType instance has the
558  /// "volatile" qualifier set, without looking through typedefs that may have
559  /// added "volatile" at a different level.
560  bool isLocalVolatileQualified() const {
561    return (getLocalFastQualifiers() & Qualifiers::Volatile);
562  }
563
564  /// \brief Determine whether this type is volatile-qualified.
565  bool isVolatileQualified() const;
566
567  /// \brief Determine whether this particular QualType instance has any
568  /// qualifiers, without looking through any typedefs that might add
569  /// qualifiers at a different level.
570  bool hasLocalQualifiers() const {
571    return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
572  }
573
574  /// \brief Determine whether this type has any qualifiers.
575  bool hasQualifiers() const;
576
577  /// \brief Determine whether this particular QualType instance has any
578  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
579  /// instance.
580  bool hasLocalNonFastQualifiers() const {
581    return Value.getPointer().is<const ExtQuals*>();
582  }
583
584  /// \brief Retrieve the set of qualifiers local to this particular QualType
585  /// instance, not including any qualifiers acquired through typedefs or
586  /// other sugar.
587  Qualifiers getLocalQualifiers() const;
588
589  /// \brief Retrieve the set of qualifiers applied to this type.
590  Qualifiers getQualifiers() const;
591
592  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
593  /// local to this particular QualType instance, not including any qualifiers
594  /// acquired through typedefs or other sugar.
595  unsigned getLocalCVRQualifiers() const {
596    return getLocalFastQualifiers();
597  }
598
599  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
600  /// applied to this type.
601  unsigned getCVRQualifiers() const;
602
603  bool isConstant(ASTContext& Ctx) const {
604    return QualType::isConstant(*this, Ctx);
605  }
606
607  /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
608  bool isPODType(ASTContext &Context) const;
609
610  /// isCXX11PODType() - Return true if this is a POD type according to the
611  /// more relaxed rules of the C++11 standard, regardless of the current
612  /// compilation's language.
613  /// (C++0x [basic.types]p9)
614  bool isCXX11PODType(ASTContext &Context) const;
615
616  /// isTrivialType - Return true if this is a trivial type
617  /// (C++0x [basic.types]p9)
618  bool isTrivialType(ASTContext &Context) const;
619
620  /// isTriviallyCopyableType - Return true if this is a trivially
621  /// copyable type (C++0x [basic.types]p9)
622  bool isTriviallyCopyableType(ASTContext &Context) const;
623
624  // Don't promise in the API that anything besides 'const' can be
625  // easily added.
626
627  /// addConst - add the specified type qualifier to this QualType.
628  void addConst() {
629    addFastQualifiers(Qualifiers::Const);
630  }
631  QualType withConst() const {
632    return withFastQualifiers(Qualifiers::Const);
633  }
634
635  /// addVolatile - add the specified type qualifier to this QualType.
636  void addVolatile() {
637    addFastQualifiers(Qualifiers::Volatile);
638  }
639  QualType withVolatile() const {
640    return withFastQualifiers(Qualifiers::Volatile);
641  }
642
643  QualType withCVRQualifiers(unsigned CVR) const {
644    return withFastQualifiers(CVR);
645  }
646
647  void addFastQualifiers(unsigned TQs) {
648    assert(!(TQs & ~Qualifiers::FastMask)
649           && "non-fast qualifier bits set in mask!");
650    Value.setInt(Value.getInt() | TQs);
651  }
652
653  void removeLocalConst();
654  void removeLocalVolatile();
655  void removeLocalRestrict();
656  void removeLocalCVRQualifiers(unsigned Mask);
657
658  void removeLocalFastQualifiers() { Value.setInt(0); }
659  void removeLocalFastQualifiers(unsigned Mask) {
660    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
661    Value.setInt(Value.getInt() & ~Mask);
662  }
663
664  // Creates a type with the given qualifiers in addition to any
665  // qualifiers already on this type.
666  QualType withFastQualifiers(unsigned TQs) const {
667    QualType T = *this;
668    T.addFastQualifiers(TQs);
669    return T;
670  }
671
672  // Creates a type with exactly the given fast qualifiers, removing
673  // any existing fast qualifiers.
674  QualType withExactLocalFastQualifiers(unsigned TQs) const {
675    return withoutLocalFastQualifiers().withFastQualifiers(TQs);
676  }
677
678  // Removes fast qualifiers, but leaves any extended qualifiers in place.
679  QualType withoutLocalFastQualifiers() const {
680    QualType T = *this;
681    T.removeLocalFastQualifiers();
682    return T;
683  }
684
685  QualType getCanonicalType() const;
686
687  /// \brief Return this type with all of the instance-specific qualifiers
688  /// removed, but without removing any qualifiers that may have been applied
689  /// through typedefs.
690  QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
691
692  /// \brief Retrieve the unqualified variant of the given type,
693  /// removing as little sugar as possible.
694  ///
695  /// This routine looks through various kinds of sugar to find the
696  /// least-desugared type that is unqualified. For example, given:
697  ///
698  /// \code
699  /// typedef int Integer;
700  /// typedef const Integer CInteger;
701  /// typedef CInteger DifferenceType;
702  /// \endcode
703  ///
704  /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
705  /// desugar until we hit the type \c Integer, which has no qualifiers on it.
706  ///
707  /// The resulting type might still be qualified if it's an array
708  /// type.  To strip qualifiers even from within an array type, use
709  /// ASTContext::getUnqualifiedArrayType.
710  inline QualType getUnqualifiedType() const;
711
712  /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
713  /// given type, removing as little sugar as possible.
714  ///
715  /// Like getUnqualifiedType(), but also returns the set of
716  /// qualifiers that were built up.
717  ///
718  /// The resulting type might still be qualified if it's an array
719  /// type.  To strip qualifiers even from within an array type, use
720  /// ASTContext::getUnqualifiedArrayType.
721  inline SplitQualType getSplitUnqualifiedType() const;
722
723  /// \brief Determine whether this type is more qualified than the other
724  /// given type, requiring exact equality for non-CVR qualifiers.
725  bool isMoreQualifiedThan(QualType Other) const;
726
727  /// \brief Determine whether this type is at least as qualified as the other
728  /// given type, requiring exact equality for non-CVR qualifiers.
729  bool isAtLeastAsQualifiedAs(QualType Other) const;
730
731  QualType getNonReferenceType() const;
732
733  /// \brief Determine the type of a (typically non-lvalue) expression with the
734  /// specified result type.
735  ///
736  /// This routine should be used for expressions for which the return type is
737  /// explicitly specified (e.g., in a cast or call) and isn't necessarily
738  /// an lvalue. It removes a top-level reference (since there are no
739  /// expressions of reference type) and deletes top-level cvr-qualifiers
740  /// from non-class types (in C++) or all types (in C).
741  QualType getNonLValueExprType(ASTContext &Context) const;
742
743  /// getDesugaredType - Return the specified type with any "sugar" removed from
744  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
745  /// the type is already concrete, it returns it unmodified.  This is similar
746  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
747  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
748  /// concrete.
749  ///
750  /// Qualifiers are left in place.
751  QualType getDesugaredType(const ASTContext &Context) const {
752    return getDesugaredType(*this, Context);
753  }
754
755  SplitQualType getSplitDesugaredType() const {
756    return getSplitDesugaredType(*this);
757  }
758
759  /// \brief Return the specified type with one level of "sugar" removed from
760  /// the type.
761  ///
762  /// This routine takes off the first typedef, typeof, etc. If the outer level
763  /// of the type is already concrete, it returns it unmodified.
764  QualType getSingleStepDesugaredType(const ASTContext &Context) const;
765
766  /// IgnoreParens - Returns the specified type after dropping any
767  /// outer-level parentheses.
768  QualType IgnoreParens() const {
769    if (isa<ParenType>(*this))
770      return QualType::IgnoreParens(*this);
771    return *this;
772  }
773
774  /// operator==/!= - Indicate whether the specified types and qualifiers are
775  /// identical.
776  friend bool operator==(const QualType &LHS, const QualType &RHS) {
777    return LHS.Value == RHS.Value;
778  }
779  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
780    return LHS.Value != RHS.Value;
781  }
782  std::string getAsString() const {
783    return getAsString(split());
784  }
785  static std::string getAsString(SplitQualType split) {
786    return getAsString(split.first, split.second);
787  }
788  static std::string getAsString(const Type *ty, Qualifiers qs);
789
790  std::string getAsString(const PrintingPolicy &Policy) const {
791    std::string S;
792    getAsStringInternal(S, Policy);
793    return S;
794  }
795  void getAsStringInternal(std::string &Str,
796                           const PrintingPolicy &Policy) const {
797    return getAsStringInternal(split(), Str, Policy);
798  }
799  static void getAsStringInternal(SplitQualType split, std::string &out,
800                                  const PrintingPolicy &policy) {
801    return getAsStringInternal(split.first, split.second, out, policy);
802  }
803  static void getAsStringInternal(const Type *ty, Qualifiers qs,
804                                  std::string &out,
805                                  const PrintingPolicy &policy);
806
807  void dump(const char *s) const;
808  void dump() const;
809
810  void Profile(llvm::FoldingSetNodeID &ID) const {
811    ID.AddPointer(getAsOpaquePtr());
812  }
813
814  /// getAddressSpace - Return the address space of this type.
815  inline unsigned getAddressSpace() const;
816
817  /// getObjCGCAttr - Returns gc attribute of this type.
818  inline Qualifiers::GC getObjCGCAttr() const;
819
820  /// isObjCGCWeak true when Type is objc's weak.
821  bool isObjCGCWeak() const {
822    return getObjCGCAttr() == Qualifiers::Weak;
823  }
824
825  /// isObjCGCStrong true when Type is objc's strong.
826  bool isObjCGCStrong() const {
827    return getObjCGCAttr() == Qualifiers::Strong;
828  }
829
830  /// getObjCLifetime - Returns lifetime attribute of this type.
831  Qualifiers::ObjCLifetime getObjCLifetime() const {
832    return getQualifiers().getObjCLifetime();
833  }
834
835  bool hasNonTrivialObjCLifetime() const {
836    return getQualifiers().hasNonTrivialObjCLifetime();
837  }
838
839  bool hasStrongOrWeakObjCLifetime() const {
840    return getQualifiers().hasStrongOrWeakObjCLifetime();
841  }
842
843  enum DestructionKind {
844    DK_none,
845    DK_cxx_destructor,
846    DK_objc_strong_lifetime,
847    DK_objc_weak_lifetime
848  };
849
850  /// isDestructedType - nonzero if objects of this type require
851  /// non-trivial work to clean up after.  Non-zero because it's
852  /// conceivable that qualifiers (objc_gc(weak)?) could make
853  /// something require destruction.
854  DestructionKind isDestructedType() const {
855    return isDestructedTypeImpl(*this);
856  }
857
858  /// \brief Determine whether expressions of the given type are forbidden
859  /// from being lvalues in C.
860  ///
861  /// The expression types that are forbidden to be lvalues are:
862  ///   - 'void', but not qualified void
863  ///   - function types
864  ///
865  /// The exact rule here is C99 6.3.2.1:
866  ///   An lvalue is an expression with an object type or an incomplete
867  ///   type other than void.
868  bool isCForbiddenLValueType() const;
869
870  /// \brief Determine whether this type has trivial copy/move-assignment
871  ///        semantics.
872  bool hasTrivialAssignment(ASTContext &Context, bool Copying) const;
873
874private:
875  // These methods are implemented in a separate translation unit;
876  // "static"-ize them to avoid creating temporary QualTypes in the
877  // caller.
878  static bool isConstant(QualType T, ASTContext& Ctx);
879  static QualType getDesugaredType(QualType T, const ASTContext &Context);
880  static SplitQualType getSplitDesugaredType(QualType T);
881  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
882  static QualType IgnoreParens(QualType T);
883  static DestructionKind isDestructedTypeImpl(QualType type);
884};
885
886} // end clang.
887
888namespace llvm {
889/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
890/// to a specific Type class.
891template<> struct simplify_type<const ::clang::QualType> {
892  typedef const ::clang::Type *SimpleType;
893  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
894    return Val.getTypePtr();
895  }
896};
897template<> struct simplify_type< ::clang::QualType>
898  : public simplify_type<const ::clang::QualType> {};
899
900// Teach SmallPtrSet that QualType is "basically a pointer".
901template<>
902class PointerLikeTypeTraits<clang::QualType> {
903public:
904  static inline void *getAsVoidPointer(clang::QualType P) {
905    return P.getAsOpaquePtr();
906  }
907  static inline clang::QualType getFromVoidPointer(void *P) {
908    return clang::QualType::getFromOpaquePtr(P);
909  }
910  // Various qualifiers go in low bits.
911  enum { NumLowBitsAvailable = 0 };
912};
913
914} // end namespace llvm
915
916namespace clang {
917
918/// \brief Base class that is common to both the \c ExtQuals and \c Type
919/// classes, which allows \c QualType to access the common fields between the
920/// two.
921///
922class ExtQualsTypeCommonBase {
923  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
924    : BaseType(baseType), CanonicalType(canon) {}
925
926  /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
927  /// a self-referential pointer (for \c Type).
928  ///
929  /// This pointer allows an efficient mapping from a QualType to its
930  /// underlying type pointer.
931  const Type *const BaseType;
932
933  /// \brief The canonical type of this type.  A QualType.
934  QualType CanonicalType;
935
936  friend class QualType;
937  friend class Type;
938  friend class ExtQuals;
939};
940
941/// ExtQuals - We can encode up to four bits in the low bits of a
942/// type pointer, but there are many more type qualifiers that we want
943/// to be able to apply to an arbitrary type.  Therefore we have this
944/// struct, intended to be heap-allocated and used by QualType to
945/// store qualifiers.
946///
947/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
948/// in three low bits on the QualType pointer; a fourth bit records whether
949/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
950/// Objective-C GC attributes) are much more rare.
951class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
952  // NOTE: changing the fast qualifiers should be straightforward as
953  // long as you don't make 'const' non-fast.
954  // 1. Qualifiers:
955  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
956  //       Fast qualifiers must occupy the low-order bits.
957  //    b) Update Qualifiers::FastWidth and FastMask.
958  // 2. QualType:
959  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
960  //    b) Update remove{Volatile,Restrict}, defined near the end of
961  //       this header.
962  // 3. ASTContext:
963  //    a) Update get{Volatile,Restrict}Type.
964
965  /// Quals - the immutable set of qualifiers applied by this
966  /// node;  always contains extended qualifiers.
967  Qualifiers Quals;
968
969  ExtQuals *this_() { return this; }
970
971public:
972  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
973    : ExtQualsTypeCommonBase(baseType,
974                             canon.isNull() ? QualType(this_(), 0) : canon),
975      Quals(quals)
976  {
977    assert(Quals.hasNonFastQualifiers()
978           && "ExtQuals created with no fast qualifiers");
979    assert(!Quals.hasFastQualifiers()
980           && "ExtQuals created with fast qualifiers");
981  }
982
983  Qualifiers getQualifiers() const { return Quals; }
984
985  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
986  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
987
988  bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
989  Qualifiers::ObjCLifetime getObjCLifetime() const {
990    return Quals.getObjCLifetime();
991  }
992
993  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
994  unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
995
996  const Type *getBaseType() const { return BaseType; }
997
998public:
999  void Profile(llvm::FoldingSetNodeID &ID) const {
1000    Profile(ID, getBaseType(), Quals);
1001  }
1002  static void Profile(llvm::FoldingSetNodeID &ID,
1003                      const Type *BaseType,
1004                      Qualifiers Quals) {
1005    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1006    ID.AddPointer(BaseType);
1007    Quals.Profile(ID);
1008  }
1009};
1010
1011/// \brief The kind of C++0x ref-qualifier associated with a function type,
1012/// which determines whether a member function's "this" object can be an
1013/// lvalue, rvalue, or neither.
1014enum RefQualifierKind {
1015  /// \brief No ref-qualifier was provided.
1016  RQ_None = 0,
1017  /// \brief An lvalue ref-qualifier was provided (\c &).
1018  RQ_LValue,
1019  /// \brief An rvalue ref-qualifier was provided (\c &&).
1020  RQ_RValue
1021};
1022
1023/// Type - This is the base class of the type hierarchy.  A central concept
1024/// with types is that each type always has a canonical type.  A canonical type
1025/// is the type with any typedef names stripped out of it or the types it
1026/// references.  For example, consider:
1027///
1028///  typedef int  foo;
1029///  typedef foo* bar;
1030///    'int *'    'foo *'    'bar'
1031///
1032/// There will be a Type object created for 'int'.  Since int is canonical, its
1033/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
1034/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
1035/// there is a PointerType that represents 'int*', which, like 'int', is
1036/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
1037/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1038/// is also 'int*'.
1039///
1040/// Non-canonical types are useful for emitting diagnostics, without losing
1041/// information about typedefs being used.  Canonical types are useful for type
1042/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1043/// about whether something has a particular form (e.g. is a function type),
1044/// because they implicitly, recursively, strip all typedefs out of a type.
1045///
1046/// Types, once created, are immutable.
1047///
1048class Type : public ExtQualsTypeCommonBase {
1049public:
1050  enum TypeClass {
1051#define TYPE(Class, Base) Class,
1052#define LAST_TYPE(Class) TypeLast = Class,
1053#define ABSTRACT_TYPE(Class, Base)
1054#include "clang/AST/TypeNodes.def"
1055    TagFirst = Record, TagLast = Enum
1056  };
1057
1058private:
1059  Type(const Type&);           // DO NOT IMPLEMENT.
1060  void operator=(const Type&); // DO NOT IMPLEMENT.
1061
1062  /// Bitfields required by the Type class.
1063  class TypeBitfields {
1064    friend class Type;
1065    template <class T> friend class TypePropertyCache;
1066
1067    /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1068    unsigned TC : 8;
1069
1070    /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1071    /// Note that this should stay at the end of the ivars for Type so that
1072    /// subclasses can pack their bitfields into the same word.
1073    unsigned Dependent : 1;
1074
1075    /// \brief Whether this type somehow involves a template parameter, even
1076    /// if the resolution of the type does not depend on a template parameter.
1077    unsigned InstantiationDependent : 1;
1078
1079    /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1080    unsigned VariablyModified : 1;
1081
1082    /// \brief Whether this type contains an unexpanded parameter pack
1083    /// (for C++0x variadic templates).
1084    unsigned ContainsUnexpandedParameterPack : 1;
1085
1086    /// \brief Nonzero if the cache (i.e. the bitfields here starting
1087    /// with 'Cache') is valid.  If so, then this is a
1088    /// LangOptions::VisibilityMode+1.
1089    mutable unsigned CacheValidAndVisibility : 2;
1090
1091    /// \brief Linkage of this type.
1092    mutable unsigned CachedLinkage : 2;
1093
1094    /// \brief Whether this type involves and local or unnamed types.
1095    mutable unsigned CachedLocalOrUnnamed : 1;
1096
1097    /// \brief FromAST - Whether this type comes from an AST file.
1098    mutable unsigned FromAST : 1;
1099
1100    bool isCacheValid() const {
1101      return (CacheValidAndVisibility != 0);
1102    }
1103    Visibility getVisibility() const {
1104      assert(isCacheValid() && "getting linkage from invalid cache");
1105      return static_cast<Visibility>(CacheValidAndVisibility-1);
1106    }
1107    Linkage getLinkage() const {
1108      assert(isCacheValid() && "getting linkage from invalid cache");
1109      return static_cast<Linkage>(CachedLinkage);
1110    }
1111    bool hasLocalOrUnnamedType() const {
1112      assert(isCacheValid() && "getting linkage from invalid cache");
1113      return CachedLocalOrUnnamed;
1114    }
1115  };
1116  enum { NumTypeBits = 18 };
1117
1118protected:
1119  // These classes allow subclasses to somewhat cleanly pack bitfields
1120  // into Type.
1121
1122  class ArrayTypeBitfields {
1123    friend class ArrayType;
1124
1125    unsigned : NumTypeBits;
1126
1127    /// IndexTypeQuals - CVR qualifiers from declarations like
1128    /// 'int X[static restrict 4]'. For function parameters only.
1129    unsigned IndexTypeQuals : 3;
1130
1131    /// SizeModifier - storage class qualifiers from declarations like
1132    /// 'int X[static restrict 4]'. For function parameters only.
1133    /// Actually an ArrayType::ArraySizeModifier.
1134    unsigned SizeModifier : 3;
1135  };
1136
1137  class BuiltinTypeBitfields {
1138    friend class BuiltinType;
1139
1140    unsigned : NumTypeBits;
1141
1142    /// The kind (BuiltinType::Kind) of builtin type this is.
1143    unsigned Kind : 8;
1144  };
1145
1146  class FunctionTypeBitfields {
1147    friend class FunctionType;
1148
1149    unsigned : NumTypeBits;
1150
1151    /// Extra information which affects how the function is called, like
1152    /// regparm and the calling convention.
1153    unsigned ExtInfo : 8;
1154
1155    /// Whether the function is variadic.  Only used by FunctionProtoType.
1156    unsigned Variadic : 1;
1157
1158    /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1159    /// other bitfields.
1160    /// The qualifiers are part of FunctionProtoType because...
1161    ///
1162    /// C++ 8.3.5p4: The return type, the parameter type list and the
1163    /// cv-qualifier-seq, [...], are part of the function type.
1164    unsigned TypeQuals : 3;
1165
1166    /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1167    ///
1168    /// This is a value of type \c RefQualifierKind.
1169    unsigned RefQualifier : 2;
1170  };
1171
1172  class ObjCObjectTypeBitfields {
1173    friend class ObjCObjectType;
1174
1175    unsigned : NumTypeBits;
1176
1177    /// NumProtocols - The number of protocols stored directly on this
1178    /// object type.
1179    unsigned NumProtocols : 32 - NumTypeBits;
1180  };
1181
1182  class ReferenceTypeBitfields {
1183    friend class ReferenceType;
1184
1185    unsigned : NumTypeBits;
1186
1187    /// True if the type was originally spelled with an lvalue sigil.
1188    /// This is never true of rvalue references but can also be false
1189    /// on lvalue references because of C++0x [dcl.typedef]p9,
1190    /// as follows:
1191    ///
1192    ///   typedef int &ref;    // lvalue, spelled lvalue
1193    ///   typedef int &&rvref; // rvalue
1194    ///   ref &a;              // lvalue, inner ref, spelled lvalue
1195    ///   ref &&a;             // lvalue, inner ref
1196    ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1197    ///   rvref &&a;           // rvalue, inner ref
1198    unsigned SpelledAsLValue : 1;
1199
1200    /// True if the inner type is a reference type.  This only happens
1201    /// in non-canonical forms.
1202    unsigned InnerRef : 1;
1203  };
1204
1205  class TypeWithKeywordBitfields {
1206    friend class TypeWithKeyword;
1207
1208    unsigned : NumTypeBits;
1209
1210    /// An ElaboratedTypeKeyword.  8 bits for efficient access.
1211    unsigned Keyword : 8;
1212  };
1213
1214  class VectorTypeBitfields {
1215    friend class VectorType;
1216
1217    unsigned : NumTypeBits;
1218
1219    /// VecKind - The kind of vector, either a generic vector type or some
1220    /// target-specific vector type such as for AltiVec or Neon.
1221    unsigned VecKind : 3;
1222
1223    /// NumElements - The number of elements in the vector.
1224    unsigned NumElements : 29 - NumTypeBits;
1225  };
1226
1227  class AttributedTypeBitfields {
1228    friend class AttributedType;
1229
1230    unsigned : NumTypeBits;
1231
1232    /// AttrKind - an AttributedType::Kind
1233    unsigned AttrKind : 32 - NumTypeBits;
1234  };
1235
1236  union {
1237    TypeBitfields TypeBits;
1238    ArrayTypeBitfields ArrayTypeBits;
1239    AttributedTypeBitfields AttributedTypeBits;
1240    BuiltinTypeBitfields BuiltinTypeBits;
1241    FunctionTypeBitfields FunctionTypeBits;
1242    ObjCObjectTypeBitfields ObjCObjectTypeBits;
1243    ReferenceTypeBitfields ReferenceTypeBits;
1244    TypeWithKeywordBitfields TypeWithKeywordBits;
1245    VectorTypeBitfields VectorTypeBits;
1246  };
1247
1248private:
1249  /// \brief Set whether this type comes from an AST file.
1250  void setFromAST(bool V = true) const {
1251    TypeBits.FromAST = V;
1252  }
1253
1254  template <class T> friend class TypePropertyCache;
1255
1256protected:
1257  // silence VC++ warning C4355: 'this' : used in base member initializer list
1258  Type *this_() { return this; }
1259  Type(TypeClass tc, QualType canon, bool Dependent,
1260       bool InstantiationDependent, bool VariablyModified,
1261       bool ContainsUnexpandedParameterPack)
1262    : ExtQualsTypeCommonBase(this,
1263                             canon.isNull() ? QualType(this_(), 0) : canon) {
1264    TypeBits.TC = tc;
1265    TypeBits.Dependent = Dependent;
1266    TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1267    TypeBits.VariablyModified = VariablyModified;
1268    TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1269    TypeBits.CacheValidAndVisibility = 0;
1270    TypeBits.CachedLocalOrUnnamed = false;
1271    TypeBits.CachedLinkage = NoLinkage;
1272    TypeBits.FromAST = false;
1273  }
1274  friend class ASTContext;
1275
1276  void setDependent(bool D = true) {
1277    TypeBits.Dependent = D;
1278    if (D)
1279      TypeBits.InstantiationDependent = true;
1280  }
1281  void setInstantiationDependent(bool D = true) {
1282    TypeBits.InstantiationDependent = D; }
1283  void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1284  }
1285  void setContainsUnexpandedParameterPack(bool PP = true) {
1286    TypeBits.ContainsUnexpandedParameterPack = PP;
1287  }
1288
1289public:
1290  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1291
1292  /// \brief Whether this type comes from an AST file.
1293  bool isFromAST() const { return TypeBits.FromAST; }
1294
1295  /// \brief Whether this type is or contains an unexpanded parameter
1296  /// pack, used to support C++0x variadic templates.
1297  ///
1298  /// A type that contains a parameter pack shall be expanded by the
1299  /// ellipsis operator at some point. For example, the typedef in the
1300  /// following example contains an unexpanded parameter pack 'T':
1301  ///
1302  /// \code
1303  /// template<typename ...T>
1304  /// struct X {
1305  ///   typedef T* pointer_types; // ill-formed; T is a parameter pack.
1306  /// };
1307  /// \endcode
1308  ///
1309  /// Note that this routine does not specify which
1310  bool containsUnexpandedParameterPack() const {
1311    return TypeBits.ContainsUnexpandedParameterPack;
1312  }
1313
1314  /// Determines if this type would be canonical if it had no further
1315  /// qualification.
1316  bool isCanonicalUnqualified() const {
1317    return CanonicalType == QualType(this, 0);
1318  }
1319
1320  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1321  /// object types, function types, and incomplete types.
1322
1323  /// isIncompleteType - Return true if this is an incomplete type.
1324  /// A type that can describe objects, but which lacks information needed to
1325  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1326  /// routine will need to determine if the size is actually required.
1327  ///
1328  /// \brief Def If non-NULL, and the type refers to some kind of declaration
1329  /// that can be completed (such as a C struct, C++ class, or Objective-C
1330  /// class), will be set to the declaration.
1331  bool isIncompleteType(NamedDecl **Def = 0) const;
1332
1333  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1334  /// type, in other words, not a function type.
1335  bool isIncompleteOrObjectType() const {
1336    return !isFunctionType();
1337  }
1338
1339  /// \brief Determine whether this type is an object type.
1340  bool isObjectType() const {
1341    // C++ [basic.types]p8:
1342    //   An object type is a (possibly cv-qualified) type that is not a
1343    //   function type, not a reference type, and not a void type.
1344    return !isReferenceType() && !isFunctionType() && !isVoidType();
1345  }
1346
1347  /// isLiteralType - Return true if this is a literal type
1348  /// (C++0x [basic.types]p10)
1349  bool isLiteralType() const;
1350
1351  /// \brief Test if this type is a standard-layout type.
1352  /// (C++0x [basic.type]p9)
1353  bool isStandardLayoutType() const;
1354
1355  /// Helper methods to distinguish type categories. All type predicates
1356  /// operate on the canonical type, ignoring typedefs and qualifiers.
1357
1358  /// isBuiltinType - returns true if the type is a builtin type.
1359  bool isBuiltinType() const;
1360
1361  /// isSpecificBuiltinType - Test for a particular builtin type.
1362  bool isSpecificBuiltinType(unsigned K) const;
1363
1364  /// isPlaceholderType - Test for a type which does not represent an
1365  /// actual type-system type but is instead used as a placeholder for
1366  /// various convenient purposes within Clang.  All such types are
1367  /// BuiltinTypes.
1368  bool isPlaceholderType() const;
1369  const BuiltinType *getAsPlaceholderType() const;
1370
1371  /// isSpecificPlaceholderType - Test for a specific placeholder type.
1372  bool isSpecificPlaceholderType(unsigned K) const;
1373
1374  /// isNonOverloadPlaceholderType - Test for a placeholder type
1375  /// other than Overload;  see BuiltinType::isNonOverloadPlaceholderType.
1376  bool isNonOverloadPlaceholderType() const;
1377
1378  /// isIntegerType() does *not* include complex integers (a GCC extension).
1379  /// isComplexIntegerType() can be used to test for complex integers.
1380  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
1381  bool isEnumeralType() const;
1382  bool isBooleanType() const;
1383  bool isCharType() const;
1384  bool isWideCharType() const;
1385  bool isChar16Type() const;
1386  bool isChar32Type() const;
1387  bool isAnyCharacterType() const;
1388  bool isIntegralType(ASTContext &Ctx) const;
1389
1390  /// \brief Determine whether this type is an integral or enumeration type.
1391  bool isIntegralOrEnumerationType() const;
1392  /// \brief Determine whether this type is an integral or unscoped enumeration
1393  /// type.
1394  bool isIntegralOrUnscopedEnumerationType() const;
1395
1396  /// Floating point categories.
1397  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1398  /// isComplexType() does *not* include complex integers (a GCC extension).
1399  /// isComplexIntegerType() can be used to test for complex integers.
1400  bool isComplexType() const;      // C99 6.2.5p11 (complex)
1401  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
1402  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
1403  bool isHalfType() const;         // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1404  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
1405  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
1406  bool isVoidType() const;         // C99 6.2.5p19
1407  bool isDerivedType() const;      // C99 6.2.5p20
1408  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
1409  bool isAggregateType() const;
1410  bool isFundamentalType() const;
1411  bool isCompoundType() const;
1412
1413  // Type Predicates: Check to see if this type is structurally the specified
1414  // type, ignoring typedefs and qualifiers.
1415  bool isFunctionType() const;
1416  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1417  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1418  bool isPointerType() const;
1419  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
1420  bool isBlockPointerType() const;
1421  bool isVoidPointerType() const;
1422  bool isReferenceType() const;
1423  bool isLValueReferenceType() const;
1424  bool isRValueReferenceType() const;
1425  bool isFunctionPointerType() const;
1426  bool isMemberPointerType() const;
1427  bool isMemberFunctionPointerType() const;
1428  bool isMemberDataPointerType() const;
1429  bool isArrayType() const;
1430  bool isConstantArrayType() const;
1431  bool isIncompleteArrayType() const;
1432  bool isVariableArrayType() const;
1433  bool isDependentSizedArrayType() const;
1434  bool isRecordType() const;
1435  bool isClassType() const;
1436  bool isStructureType() const;
1437  bool isStructureOrClassType() const;
1438  bool isUnionType() const;
1439  bool isComplexIntegerType() const;            // GCC _Complex integer type.
1440  bool isVectorType() const;                    // GCC vector type.
1441  bool isExtVectorType() const;                 // Extended vector type.
1442  bool isObjCObjectPointerType() const;         // pointer to ObjC object
1443  bool isObjCRetainableType() const;            // ObjC object or block pointer
1444  bool isObjCLifetimeType() const;              // (array of)* retainable type
1445  bool isObjCIndirectLifetimeType() const;      // (pointer to)* lifetime type
1446  bool isObjCNSObjectType() const;              // __attribute__((NSObject))
1447  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1448  // for the common case.
1449  bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
1450  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
1451  bool isObjCQualifiedIdType() const;           // id<foo>
1452  bool isObjCQualifiedClassType() const;        // Class<foo>
1453  bool isObjCObjectOrInterfaceType() const;
1454  bool isObjCIdType() const;                    // id
1455  bool isObjCClassType() const;                 // Class
1456  bool isObjCSelType() const;                 // Class
1457  bool isObjCBuiltinType() const;               // 'id' or 'Class'
1458  bool isObjCARCBridgableType() const;
1459  bool isCARCBridgableType() const;
1460  bool isTemplateTypeParmType() const;          // C++ template type parameter
1461  bool isNullPtrType() const;                   // C++0x nullptr_t
1462  bool isAtomicType() const;                    // C11 _Atomic()
1463
1464  /// Determines if this type, which must satisfy
1465  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1466  /// than implicitly __strong.
1467  bool isObjCARCImplicitlyUnretainedType() const;
1468
1469  /// Return the implicit lifetime for this type, which must not be dependent.
1470  Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1471
1472  enum ScalarTypeKind {
1473    STK_CPointer,
1474    STK_BlockPointer,
1475    STK_ObjCObjectPointer,
1476    STK_MemberPointer,
1477    STK_Bool,
1478    STK_Integral,
1479    STK_Floating,
1480    STK_IntegralComplex,
1481    STK_FloatingComplex
1482  };
1483  /// getScalarTypeKind - Given that this is a scalar type, classify it.
1484  ScalarTypeKind getScalarTypeKind() const;
1485
1486  /// isDependentType - Whether this type is a dependent type, meaning
1487  /// that its definition somehow depends on a template parameter
1488  /// (C++ [temp.dep.type]).
1489  bool isDependentType() const { return TypeBits.Dependent; }
1490
1491  /// \brief Determine whether this type is an instantiation-dependent type,
1492  /// meaning that the type involves a template parameter (even if the
1493  /// definition does not actually depend on the type substituted for that
1494  /// template parameter).
1495  bool isInstantiationDependentType() const {
1496    return TypeBits.InstantiationDependent;
1497  }
1498
1499  /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1500  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1501
1502  /// \brief Whether this type involves a variable-length array type
1503  /// with a definite size.
1504  bool hasSizedVLAType() const;
1505
1506  /// \brief Whether this type is or contains a local or unnamed type.
1507  bool hasUnnamedOrLocalType() const;
1508
1509  bool isOverloadableType() const;
1510
1511  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1512  bool isElaboratedTypeSpecifier() const;
1513
1514  bool canDecayToPointerType() const;
1515
1516  /// hasPointerRepresentation - Whether this type is represented
1517  /// natively as a pointer; this includes pointers, references, block
1518  /// pointers, and Objective-C interface, qualified id, and qualified
1519  /// interface types, as well as nullptr_t.
1520  bool hasPointerRepresentation() const;
1521
1522  /// hasObjCPointerRepresentation - Whether this type can represent
1523  /// an objective pointer type for the purpose of GC'ability
1524  bool hasObjCPointerRepresentation() const;
1525
1526  /// \brief Determine whether this type has an integer representation
1527  /// of some sort, e.g., it is an integer type or a vector.
1528  bool hasIntegerRepresentation() const;
1529
1530  /// \brief Determine whether this type has an signed integer representation
1531  /// of some sort, e.g., it is an signed integer type or a vector.
1532  bool hasSignedIntegerRepresentation() const;
1533
1534  /// \brief Determine whether this type has an unsigned integer representation
1535  /// of some sort, e.g., it is an unsigned integer type or a vector.
1536  bool hasUnsignedIntegerRepresentation() const;
1537
1538  /// \brief Determine whether this type has a floating-point representation
1539  /// of some sort, e.g., it is a floating-point type or a vector thereof.
1540  bool hasFloatingRepresentation() const;
1541
1542  // Type Checking Functions: Check to see if this type is structurally the
1543  // specified type, ignoring typedefs and qualifiers, and return a pointer to
1544  // the best type we can.
1545  const RecordType *getAsStructureType() const;
1546  /// NOTE: getAs*ArrayType are methods on ASTContext.
1547  const RecordType *getAsUnionType() const;
1548  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1549  // The following is a convenience method that returns an ObjCObjectPointerType
1550  // for object declared using an interface.
1551  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1552  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1553  const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1554  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1555  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
1556
1557  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1558  /// because the type is a RecordType or because it is the injected-class-name
1559  /// type of a class template or class template partial specialization.
1560  CXXRecordDecl *getAsCXXRecordDecl() const;
1561
1562  /// \brief Get the AutoType whose type will be deduced for a variable with
1563  /// an initializer of this type. This looks through declarators like pointer
1564  /// types, but not through decltype or typedefs.
1565  AutoType *getContainedAutoType() const;
1566
1567  /// Member-template getAs<specific type>'.  Look through sugar for
1568  /// an instance of <specific type>.   This scheme will eventually
1569  /// replace the specific getAsXXXX methods above.
1570  ///
1571  /// There are some specializations of this member template listed
1572  /// immediately following this class.
1573  template <typename T> const T *getAs() const;
1574
1575  /// A variant of getAs<> for array types which silently discards
1576  /// qualifiers from the outermost type.
1577  const ArrayType *getAsArrayTypeUnsafe() const;
1578
1579  /// Member-template castAs<specific type>.  Look through sugar for
1580  /// the underlying instance of <specific type>.
1581  ///
1582  /// This method has the same relationship to getAs<T> as cast<T> has
1583  /// to dyn_cast<T>; which is to say, the underlying type *must*
1584  /// have the intended type, and this method will never return null.
1585  template <typename T> const T *castAs() const;
1586
1587  /// A variant of castAs<> for array type which silently discards
1588  /// qualifiers from the outermost type.
1589  const ArrayType *castAsArrayTypeUnsafe() const;
1590
1591  /// getBaseElementTypeUnsafe - Get the base element type of this
1592  /// type, potentially discarding type qualifiers.  This method
1593  /// should never be used when type qualifiers are meaningful.
1594  const Type *getBaseElementTypeUnsafe() const;
1595
1596  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1597  /// element type of the array, potentially with type qualifiers missing.
1598  /// This method should never be used when type qualifiers are meaningful.
1599  const Type *getArrayElementTypeNoTypeQual() const;
1600
1601  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1602  /// pointer, this returns the respective pointee.
1603  QualType getPointeeType() const;
1604
1605  /// getUnqualifiedDesugaredType() - Return the specified type with
1606  /// any "sugar" removed from the type, removing any typedefs,
1607  /// typeofs, etc., as well as any qualifiers.
1608  const Type *getUnqualifiedDesugaredType() const;
1609
1610  /// More type predicates useful for type checking/promotion
1611  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1612
1613  /// isSignedIntegerType - Return true if this is an integer type that is
1614  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1615  /// or an enum decl which has a signed representation.
1616  bool isSignedIntegerType() const;
1617
1618  /// isUnsignedIntegerType - Return true if this is an integer type that is
1619  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1620  /// or an enum decl which has an unsigned representation.
1621  bool isUnsignedIntegerType() const;
1622
1623  /// Determines whether this is an integer type that is signed or an
1624  /// enumeration types whose underlying type is a signed integer type.
1625  bool isSignedIntegerOrEnumerationType() const;
1626
1627  /// Determines whether this is an integer type that is unsigned or an
1628  /// enumeration types whose underlying type is a unsigned integer type.
1629  bool isUnsignedIntegerOrEnumerationType() const;
1630
1631  /// isConstantSizeType - Return true if this is not a variable sized type,
1632  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1633  /// incomplete types.
1634  bool isConstantSizeType() const;
1635
1636  /// isSpecifierType - Returns true if this type can be represented by some
1637  /// set of type specifiers.
1638  bool isSpecifierType() const;
1639
1640  /// \brief Determine the linkage of this type.
1641  Linkage getLinkage() const;
1642
1643  /// \brief Determine the visibility of this type.
1644  Visibility getVisibility() const;
1645
1646  /// \brief Determine the linkage and visibility of this type.
1647  std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1648
1649  /// \brief Note that the linkage is no longer known.
1650  void ClearLinkageCache();
1651
1652  const char *getTypeClassName() const;
1653
1654  QualType getCanonicalTypeInternal() const {
1655    return CanonicalType;
1656  }
1657  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1658  void dump() const;
1659
1660  static bool classof(const Type *) { return true; }
1661
1662  friend class ASTReader;
1663  friend class ASTWriter;
1664};
1665
1666template <> inline const TypedefType *Type::getAs() const {
1667  return dyn_cast<TypedefType>(this);
1668}
1669
1670// We can do canonical leaf types faster, because we don't have to
1671// worry about preserving child type decoration.
1672#define TYPE(Class, Base)
1673#define LEAF_TYPE(Class) \
1674template <> inline const Class##Type *Type::getAs() const { \
1675  return dyn_cast<Class##Type>(CanonicalType); \
1676} \
1677template <> inline const Class##Type *Type::castAs() const { \
1678  return cast<Class##Type>(CanonicalType); \
1679}
1680#include "clang/AST/TypeNodes.def"
1681
1682
1683/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1684/// types are always canonical and have a literal name field.
1685class BuiltinType : public Type {
1686public:
1687  enum Kind {
1688#define BUILTIN_TYPE(Id, SingletonId) Id,
1689#define LAST_BUILTIN_TYPE(Id) LastKind = Id
1690#include "clang/AST/BuiltinTypes.def"
1691  };
1692
1693public:
1694  BuiltinType(Kind K)
1695    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1696           /*InstantiationDependent=*/(K == Dependent),
1697           /*VariablyModified=*/false,
1698           /*Unexpanded paramter pack=*/false) {
1699    BuiltinTypeBits.Kind = K;
1700  }
1701
1702  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1703  const char *getName(const PrintingPolicy &Policy) const;
1704
1705  bool isSugared() const { return false; }
1706  QualType desugar() const { return QualType(this, 0); }
1707
1708  bool isInteger() const {
1709    return getKind() >= Bool && getKind() <= Int128;
1710  }
1711
1712  bool isSignedInteger() const {
1713    return getKind() >= Char_S && getKind() <= Int128;
1714  }
1715
1716  bool isUnsignedInteger() const {
1717    return getKind() >= Bool && getKind() <= UInt128;
1718  }
1719
1720  bool isFloatingPoint() const {
1721    return getKind() >= Half && getKind() <= LongDouble;
1722  }
1723
1724  /// Determines whether the given kind corresponds to a placeholder type.
1725  static bool isPlaceholderTypeKind(Kind K) {
1726    return K >= Overload;
1727  }
1728
1729  /// Determines whether this type is a placeholder type, i.e. a type
1730  /// which cannot appear in arbitrary positions in a fully-formed
1731  /// expression.
1732  bool isPlaceholderType() const {
1733    return isPlaceholderTypeKind(getKind());
1734  }
1735
1736  /// Determines whether this type is a placeholder type other than
1737  /// Overload.  Most placeholder types require only syntactic
1738  /// information about their context in order to be resolved (e.g.
1739  /// whether it is a call expression), which means they can (and
1740  /// should) be resolved in an earlier "phase" of analysis.
1741  /// Overload expressions sometimes pick up further information
1742  /// from their context, like whether the context expects a
1743  /// specific function-pointer type, and so frequently need
1744  /// special treatment.
1745  bool isNonOverloadPlaceholderType() const {
1746    return getKind() > Overload;
1747  }
1748
1749  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1750  static bool classof(const BuiltinType *) { return true; }
1751};
1752
1753/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1754/// types (_Complex float etc) as well as the GCC integer complex extensions.
1755///
1756class ComplexType : public Type, public llvm::FoldingSetNode {
1757  QualType ElementType;
1758  ComplexType(QualType Element, QualType CanonicalPtr) :
1759    Type(Complex, CanonicalPtr, Element->isDependentType(),
1760         Element->isInstantiationDependentType(),
1761         Element->isVariablyModifiedType(),
1762         Element->containsUnexpandedParameterPack()),
1763    ElementType(Element) {
1764  }
1765  friend class ASTContext;  // ASTContext creates these.
1766
1767public:
1768  QualType getElementType() const { return ElementType; }
1769
1770  bool isSugared() const { return false; }
1771  QualType desugar() const { return QualType(this, 0); }
1772
1773  void Profile(llvm::FoldingSetNodeID &ID) {
1774    Profile(ID, getElementType());
1775  }
1776  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1777    ID.AddPointer(Element.getAsOpaquePtr());
1778  }
1779
1780  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1781  static bool classof(const ComplexType *) { return true; }
1782};
1783
1784/// ParenType - Sugar for parentheses used when specifying types.
1785///
1786class ParenType : public Type, public llvm::FoldingSetNode {
1787  QualType Inner;
1788
1789  ParenType(QualType InnerType, QualType CanonType) :
1790    Type(Paren, CanonType, InnerType->isDependentType(),
1791         InnerType->isInstantiationDependentType(),
1792         InnerType->isVariablyModifiedType(),
1793         InnerType->containsUnexpandedParameterPack()),
1794    Inner(InnerType) {
1795  }
1796  friend class ASTContext;  // ASTContext creates these.
1797
1798public:
1799
1800  QualType getInnerType() const { return Inner; }
1801
1802  bool isSugared() const { return true; }
1803  QualType desugar() const { return getInnerType(); }
1804
1805  void Profile(llvm::FoldingSetNodeID &ID) {
1806    Profile(ID, getInnerType());
1807  }
1808  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1809    Inner.Profile(ID);
1810  }
1811
1812  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1813  static bool classof(const ParenType *) { return true; }
1814};
1815
1816/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1817///
1818class PointerType : public Type, public llvm::FoldingSetNode {
1819  QualType PointeeType;
1820
1821  PointerType(QualType Pointee, QualType CanonicalPtr) :
1822    Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1823         Pointee->isInstantiationDependentType(),
1824         Pointee->isVariablyModifiedType(),
1825         Pointee->containsUnexpandedParameterPack()),
1826    PointeeType(Pointee) {
1827  }
1828  friend class ASTContext;  // ASTContext creates these.
1829
1830public:
1831
1832  QualType getPointeeType() const { return PointeeType; }
1833
1834  bool isSugared() const { return false; }
1835  QualType desugar() const { return QualType(this, 0); }
1836
1837  void Profile(llvm::FoldingSetNodeID &ID) {
1838    Profile(ID, getPointeeType());
1839  }
1840  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1841    ID.AddPointer(Pointee.getAsOpaquePtr());
1842  }
1843
1844  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1845  static bool classof(const PointerType *) { return true; }
1846};
1847
1848/// BlockPointerType - pointer to a block type.
1849/// This type is to represent types syntactically represented as
1850/// "void (^)(int)", etc. Pointee is required to always be a function type.
1851///
1852class BlockPointerType : public Type, public llvm::FoldingSetNode {
1853  QualType PointeeType;  // Block is some kind of pointer type
1854  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1855    Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1856         Pointee->isInstantiationDependentType(),
1857         Pointee->isVariablyModifiedType(),
1858         Pointee->containsUnexpandedParameterPack()),
1859    PointeeType(Pointee) {
1860  }
1861  friend class ASTContext;  // ASTContext creates these.
1862
1863public:
1864
1865  // Get the pointee type. Pointee is required to always be a function type.
1866  QualType getPointeeType() const { return PointeeType; }
1867
1868  bool isSugared() const { return false; }
1869  QualType desugar() const { return QualType(this, 0); }
1870
1871  void Profile(llvm::FoldingSetNodeID &ID) {
1872      Profile(ID, getPointeeType());
1873  }
1874  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1875      ID.AddPointer(Pointee.getAsOpaquePtr());
1876  }
1877
1878  static bool classof(const Type *T) {
1879    return T->getTypeClass() == BlockPointer;
1880  }
1881  static bool classof(const BlockPointerType *) { return true; }
1882};
1883
1884/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1885///
1886class ReferenceType : public Type, public llvm::FoldingSetNode {
1887  QualType PointeeType;
1888
1889protected:
1890  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1891                bool SpelledAsLValue) :
1892    Type(tc, CanonicalRef, Referencee->isDependentType(),
1893         Referencee->isInstantiationDependentType(),
1894         Referencee->isVariablyModifiedType(),
1895         Referencee->containsUnexpandedParameterPack()),
1896    PointeeType(Referencee)
1897  {
1898    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1899    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1900  }
1901
1902public:
1903  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1904  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1905
1906  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1907  QualType getPointeeType() const {
1908    // FIXME: this might strip inner qualifiers; okay?
1909    const ReferenceType *T = this;
1910    while (T->isInnerRef())
1911      T = T->PointeeType->castAs<ReferenceType>();
1912    return T->PointeeType;
1913  }
1914
1915  void Profile(llvm::FoldingSetNodeID &ID) {
1916    Profile(ID, PointeeType, isSpelledAsLValue());
1917  }
1918  static void Profile(llvm::FoldingSetNodeID &ID,
1919                      QualType Referencee,
1920                      bool SpelledAsLValue) {
1921    ID.AddPointer(Referencee.getAsOpaquePtr());
1922    ID.AddBoolean(SpelledAsLValue);
1923  }
1924
1925  static bool classof(const Type *T) {
1926    return T->getTypeClass() == LValueReference ||
1927           T->getTypeClass() == RValueReference;
1928  }
1929  static bool classof(const ReferenceType *) { return true; }
1930};
1931
1932/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1933///
1934class LValueReferenceType : public ReferenceType {
1935  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1936                      bool SpelledAsLValue) :
1937    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1938  {}
1939  friend class ASTContext; // ASTContext creates these
1940public:
1941  bool isSugared() const { return false; }
1942  QualType desugar() const { return QualType(this, 0); }
1943
1944  static bool classof(const Type *T) {
1945    return T->getTypeClass() == LValueReference;
1946  }
1947  static bool classof(const LValueReferenceType *) { return true; }
1948};
1949
1950/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1951///
1952class RValueReferenceType : public ReferenceType {
1953  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1954    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1955  }
1956  friend class ASTContext; // ASTContext creates these
1957public:
1958  bool isSugared() const { return false; }
1959  QualType desugar() const { return QualType(this, 0); }
1960
1961  static bool classof(const Type *T) {
1962    return T->getTypeClass() == RValueReference;
1963  }
1964  static bool classof(const RValueReferenceType *) { return true; }
1965};
1966
1967/// MemberPointerType - C++ 8.3.3 - Pointers to members
1968///
1969class MemberPointerType : public Type, public llvm::FoldingSetNode {
1970  QualType PointeeType;
1971  /// The class of which the pointee is a member. Must ultimately be a
1972  /// RecordType, but could be a typedef or a template parameter too.
1973  const Type *Class;
1974
1975  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1976    Type(MemberPointer, CanonicalPtr,
1977         Cls->isDependentType() || Pointee->isDependentType(),
1978         (Cls->isInstantiationDependentType() ||
1979          Pointee->isInstantiationDependentType()),
1980         Pointee->isVariablyModifiedType(),
1981         (Cls->containsUnexpandedParameterPack() ||
1982          Pointee->containsUnexpandedParameterPack())),
1983    PointeeType(Pointee), Class(Cls) {
1984  }
1985  friend class ASTContext; // ASTContext creates these.
1986
1987public:
1988  QualType getPointeeType() const { return PointeeType; }
1989
1990  /// Returns true if the member type (i.e. the pointee type) is a
1991  /// function type rather than a data-member type.
1992  bool isMemberFunctionPointer() const {
1993    return PointeeType->isFunctionProtoType();
1994  }
1995
1996  /// Returns true if the member type (i.e. the pointee type) is a
1997  /// data type rather than a function type.
1998  bool isMemberDataPointer() const {
1999    return !PointeeType->isFunctionProtoType();
2000  }
2001
2002  const Type *getClass() const { return Class; }
2003
2004  bool isSugared() const { return false; }
2005  QualType desugar() const { return QualType(this, 0); }
2006
2007  void Profile(llvm::FoldingSetNodeID &ID) {
2008    Profile(ID, getPointeeType(), getClass());
2009  }
2010  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2011                      const Type *Class) {
2012    ID.AddPointer(Pointee.getAsOpaquePtr());
2013    ID.AddPointer(Class);
2014  }
2015
2016  static bool classof(const Type *T) {
2017    return T->getTypeClass() == MemberPointer;
2018  }
2019  static bool classof(const MemberPointerType *) { return true; }
2020};
2021
2022/// ArrayType - C99 6.7.5.2 - Array Declarators.
2023///
2024class ArrayType : public Type, public llvm::FoldingSetNode {
2025public:
2026  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2027  /// an array with a static size (e.g. int X[static 4]), or an array
2028  /// with a star size (e.g. int X[*]).
2029  /// 'static' is only allowed on function parameters.
2030  enum ArraySizeModifier {
2031    Normal, Static, Star
2032  };
2033private:
2034  /// ElementType - The element type of the array.
2035  QualType ElementType;
2036
2037protected:
2038  // C++ [temp.dep.type]p1:
2039  //   A type is dependent if it is...
2040  //     - an array type constructed from any dependent type or whose
2041  //       size is specified by a constant expression that is
2042  //       value-dependent,
2043  ArrayType(TypeClass tc, QualType et, QualType can,
2044            ArraySizeModifier sm, unsigned tq,
2045            bool ContainsUnexpandedParameterPack)
2046    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2047           et->isInstantiationDependentType() || tc == DependentSizedArray,
2048           (tc == VariableArray || et->isVariablyModifiedType()),
2049           ContainsUnexpandedParameterPack),
2050      ElementType(et) {
2051    ArrayTypeBits.IndexTypeQuals = tq;
2052    ArrayTypeBits.SizeModifier = sm;
2053  }
2054
2055  friend class ASTContext;  // ASTContext creates these.
2056
2057public:
2058  QualType getElementType() const { return ElementType; }
2059  ArraySizeModifier getSizeModifier() const {
2060    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2061  }
2062  Qualifiers getIndexTypeQualifiers() const {
2063    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2064  }
2065  unsigned getIndexTypeCVRQualifiers() const {
2066    return ArrayTypeBits.IndexTypeQuals;
2067  }
2068
2069  static bool classof(const Type *T) {
2070    return T->getTypeClass() == ConstantArray ||
2071           T->getTypeClass() == VariableArray ||
2072           T->getTypeClass() == IncompleteArray ||
2073           T->getTypeClass() == DependentSizedArray;
2074  }
2075  static bool classof(const ArrayType *) { return true; }
2076};
2077
2078/// ConstantArrayType - This class represents the canonical version of
2079/// C arrays with a specified constant size.  For example, the canonical
2080/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2081/// type is 'int' and the size is 404.
2082class ConstantArrayType : public ArrayType {
2083  llvm::APInt Size; // Allows us to unique the type.
2084
2085  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2086                    ArraySizeModifier sm, unsigned tq)
2087    : ArrayType(ConstantArray, et, can, sm, tq,
2088                et->containsUnexpandedParameterPack()),
2089      Size(size) {}
2090protected:
2091  ConstantArrayType(TypeClass tc, QualType et, QualType can,
2092                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2093    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2094      Size(size) {}
2095  friend class ASTContext;  // ASTContext creates these.
2096public:
2097  const llvm::APInt &getSize() const { return Size; }
2098  bool isSugared() const { return false; }
2099  QualType desugar() const { return QualType(this, 0); }
2100
2101
2102  /// \brief Determine the number of bits required to address a member of
2103  // an array with the given element type and number of elements.
2104  static unsigned getNumAddressingBits(ASTContext &Context,
2105                                       QualType ElementType,
2106                                       const llvm::APInt &NumElements);
2107
2108  /// \brief Determine the maximum number of active bits that an array's size
2109  /// can require, which limits the maximum size of the array.
2110  static unsigned getMaxSizeBits(ASTContext &Context);
2111
2112  void Profile(llvm::FoldingSetNodeID &ID) {
2113    Profile(ID, getElementType(), getSize(),
2114            getSizeModifier(), getIndexTypeCVRQualifiers());
2115  }
2116  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2117                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2118                      unsigned TypeQuals) {
2119    ID.AddPointer(ET.getAsOpaquePtr());
2120    ID.AddInteger(ArraySize.getZExtValue());
2121    ID.AddInteger(SizeMod);
2122    ID.AddInteger(TypeQuals);
2123  }
2124  static bool classof(const Type *T) {
2125    return T->getTypeClass() == ConstantArray;
2126  }
2127  static bool classof(const ConstantArrayType *) { return true; }
2128};
2129
2130/// IncompleteArrayType - This class represents C arrays with an unspecified
2131/// size.  For example 'int A[]' has an IncompleteArrayType where the element
2132/// type is 'int' and the size is unspecified.
2133class IncompleteArrayType : public ArrayType {
2134
2135  IncompleteArrayType(QualType et, QualType can,
2136                      ArraySizeModifier sm, unsigned tq)
2137    : ArrayType(IncompleteArray, et, can, sm, tq,
2138                et->containsUnexpandedParameterPack()) {}
2139  friend class ASTContext;  // ASTContext creates these.
2140public:
2141  bool isSugared() const { return false; }
2142  QualType desugar() const { return QualType(this, 0); }
2143
2144  static bool classof(const Type *T) {
2145    return T->getTypeClass() == IncompleteArray;
2146  }
2147  static bool classof(const IncompleteArrayType *) { return true; }
2148
2149  friend class StmtIteratorBase;
2150
2151  void Profile(llvm::FoldingSetNodeID &ID) {
2152    Profile(ID, getElementType(), getSizeModifier(),
2153            getIndexTypeCVRQualifiers());
2154  }
2155
2156  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2157                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
2158    ID.AddPointer(ET.getAsOpaquePtr());
2159    ID.AddInteger(SizeMod);
2160    ID.AddInteger(TypeQuals);
2161  }
2162};
2163
2164/// VariableArrayType - This class represents C arrays with a specified size
2165/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
2166/// Since the size expression is an arbitrary expression, we store it as such.
2167///
2168/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2169/// should not be: two lexically equivalent variable array types could mean
2170/// different things, for example, these variables do not have the same type
2171/// dynamically:
2172///
2173/// void foo(int x) {
2174///   int Y[x];
2175///   ++x;
2176///   int Z[x];
2177/// }
2178///
2179class VariableArrayType : public ArrayType {
2180  /// SizeExpr - An assignment expression. VLA's are only permitted within
2181  /// a function block.
2182  Stmt *SizeExpr;
2183  /// Brackets - The left and right array brackets.
2184  SourceRange Brackets;
2185
2186  VariableArrayType(QualType et, QualType can, Expr *e,
2187                    ArraySizeModifier sm, unsigned tq,
2188                    SourceRange brackets)
2189    : ArrayType(VariableArray, et, can, sm, tq,
2190                et->containsUnexpandedParameterPack()),
2191      SizeExpr((Stmt*) e), Brackets(brackets) {}
2192  friend class ASTContext;  // ASTContext creates these.
2193
2194public:
2195  Expr *getSizeExpr() const {
2196    // We use C-style casts instead of cast<> here because we do not wish
2197    // to have a dependency of Type.h on Stmt.h/Expr.h.
2198    return (Expr*) SizeExpr;
2199  }
2200  SourceRange getBracketsRange() const { return Brackets; }
2201  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2202  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2203
2204  bool isSugared() const { return false; }
2205  QualType desugar() const { return QualType(this, 0); }
2206
2207  static bool classof(const Type *T) {
2208    return T->getTypeClass() == VariableArray;
2209  }
2210  static bool classof(const VariableArrayType *) { return true; }
2211
2212  friend class StmtIteratorBase;
2213
2214  void Profile(llvm::FoldingSetNodeID &ID) {
2215    llvm_unreachable("Cannot unique VariableArrayTypes.");
2216  }
2217};
2218
2219/// DependentSizedArrayType - This type represents an array type in
2220/// C++ whose size is a value-dependent expression. For example:
2221///
2222/// \code
2223/// template<typename T, int Size>
2224/// class array {
2225///   T data[Size];
2226/// };
2227/// \endcode
2228///
2229/// For these types, we won't actually know what the array bound is
2230/// until template instantiation occurs, at which point this will
2231/// become either a ConstantArrayType or a VariableArrayType.
2232class DependentSizedArrayType : public ArrayType {
2233  const ASTContext &Context;
2234
2235  /// \brief An assignment expression that will instantiate to the
2236  /// size of the array.
2237  ///
2238  /// The expression itself might be NULL, in which case the array
2239  /// type will have its size deduced from an initializer.
2240  Stmt *SizeExpr;
2241
2242  /// Brackets - The left and right array brackets.
2243  SourceRange Brackets;
2244
2245  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2246                          Expr *e, ArraySizeModifier sm, unsigned tq,
2247                          SourceRange brackets);
2248
2249  friend class ASTContext;  // ASTContext creates these.
2250
2251public:
2252  Expr *getSizeExpr() const {
2253    // We use C-style casts instead of cast<> here because we do not wish
2254    // to have a dependency of Type.h on Stmt.h/Expr.h.
2255    return (Expr*) SizeExpr;
2256  }
2257  SourceRange getBracketsRange() const { return Brackets; }
2258  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2259  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2260
2261  bool isSugared() const { return false; }
2262  QualType desugar() const { return QualType(this, 0); }
2263
2264  static bool classof(const Type *T) {
2265    return T->getTypeClass() == DependentSizedArray;
2266  }
2267  static bool classof(const DependentSizedArrayType *) { return true; }
2268
2269  friend class StmtIteratorBase;
2270
2271
2272  void Profile(llvm::FoldingSetNodeID &ID) {
2273    Profile(ID, Context, getElementType(),
2274            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2275  }
2276
2277  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2278                      QualType ET, ArraySizeModifier SizeMod,
2279                      unsigned TypeQuals, Expr *E);
2280};
2281
2282/// DependentSizedExtVectorType - This type represent an extended vector type
2283/// where either the type or size is dependent. For example:
2284/// @code
2285/// template<typename T, int Size>
2286/// class vector {
2287///   typedef T __attribute__((ext_vector_type(Size))) type;
2288/// }
2289/// @endcode
2290class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2291  const ASTContext &Context;
2292  Expr *SizeExpr;
2293  /// ElementType - The element type of the array.
2294  QualType ElementType;
2295  SourceLocation loc;
2296
2297  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2298                              QualType can, Expr *SizeExpr, SourceLocation loc);
2299
2300  friend class ASTContext;
2301
2302public:
2303  Expr *getSizeExpr() const { return SizeExpr; }
2304  QualType getElementType() const { return ElementType; }
2305  SourceLocation getAttributeLoc() const { return loc; }
2306
2307  bool isSugared() const { return false; }
2308  QualType desugar() const { return QualType(this, 0); }
2309
2310  static bool classof(const Type *T) {
2311    return T->getTypeClass() == DependentSizedExtVector;
2312  }
2313  static bool classof(const DependentSizedExtVectorType *) { return true; }
2314
2315  void Profile(llvm::FoldingSetNodeID &ID) {
2316    Profile(ID, Context, getElementType(), getSizeExpr());
2317  }
2318
2319  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2320                      QualType ElementType, Expr *SizeExpr);
2321};
2322
2323
2324/// VectorType - GCC generic vector type. This type is created using
2325/// __attribute__((vector_size(n)), where "n" specifies the vector size in
2326/// bytes; or from an Altivec __vector or vector declaration.
2327/// Since the constructor takes the number of vector elements, the
2328/// client is responsible for converting the size into the number of elements.
2329class VectorType : public Type, public llvm::FoldingSetNode {
2330public:
2331  enum VectorKind {
2332    GenericVector,  // not a target-specific vector type
2333    AltiVecVector,  // is AltiVec vector
2334    AltiVecPixel,   // is AltiVec 'vector Pixel'
2335    AltiVecBool,    // is AltiVec 'vector bool ...'
2336    NeonVector,     // is ARM Neon vector
2337    NeonPolyVector  // is ARM Neon polynomial vector
2338  };
2339protected:
2340  /// ElementType - The element type of the vector.
2341  QualType ElementType;
2342
2343  VectorType(QualType vecType, unsigned nElements, QualType canonType,
2344             VectorKind vecKind);
2345
2346  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2347             QualType canonType, VectorKind vecKind);
2348
2349  friend class ASTContext;  // ASTContext creates these.
2350
2351public:
2352
2353  QualType getElementType() const { return ElementType; }
2354  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2355
2356  bool isSugared() const { return false; }
2357  QualType desugar() const { return QualType(this, 0); }
2358
2359  VectorKind getVectorKind() const {
2360    return VectorKind(VectorTypeBits.VecKind);
2361  }
2362
2363  void Profile(llvm::FoldingSetNodeID &ID) {
2364    Profile(ID, getElementType(), getNumElements(),
2365            getTypeClass(), getVectorKind());
2366  }
2367  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2368                      unsigned NumElements, TypeClass TypeClass,
2369                      VectorKind VecKind) {
2370    ID.AddPointer(ElementType.getAsOpaquePtr());
2371    ID.AddInteger(NumElements);
2372    ID.AddInteger(TypeClass);
2373    ID.AddInteger(VecKind);
2374  }
2375
2376  static bool classof(const Type *T) {
2377    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2378  }
2379  static bool classof(const VectorType *) { return true; }
2380};
2381
2382/// ExtVectorType - Extended vector type. This type is created using
2383/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2384/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2385/// class enables syntactic extensions, like Vector Components for accessing
2386/// points, colors, and textures (modeled after OpenGL Shading Language).
2387class ExtVectorType : public VectorType {
2388  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2389    VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2390  friend class ASTContext;  // ASTContext creates these.
2391public:
2392  static int getPointAccessorIdx(char c) {
2393    switch (c) {
2394    default: return -1;
2395    case 'x': return 0;
2396    case 'y': return 1;
2397    case 'z': return 2;
2398    case 'w': return 3;
2399    }
2400  }
2401  static int getNumericAccessorIdx(char c) {
2402    switch (c) {
2403      default: return -1;
2404      case '0': return 0;
2405      case '1': return 1;
2406      case '2': return 2;
2407      case '3': return 3;
2408      case '4': return 4;
2409      case '5': return 5;
2410      case '6': return 6;
2411      case '7': return 7;
2412      case '8': return 8;
2413      case '9': return 9;
2414      case 'A':
2415      case 'a': return 10;
2416      case 'B':
2417      case 'b': return 11;
2418      case 'C':
2419      case 'c': return 12;
2420      case 'D':
2421      case 'd': return 13;
2422      case 'E':
2423      case 'e': return 14;
2424      case 'F':
2425      case 'f': return 15;
2426    }
2427  }
2428
2429  static int getAccessorIdx(char c) {
2430    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2431    return getNumericAccessorIdx(c);
2432  }
2433
2434  bool isAccessorWithinNumElements(char c) const {
2435    if (int idx = getAccessorIdx(c)+1)
2436      return unsigned(idx-1) < getNumElements();
2437    return false;
2438  }
2439  bool isSugared() const { return false; }
2440  QualType desugar() const { return QualType(this, 0); }
2441
2442  static bool classof(const Type *T) {
2443    return T->getTypeClass() == ExtVector;
2444  }
2445  static bool classof(const ExtVectorType *) { return true; }
2446};
2447
2448/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2449/// class of FunctionNoProtoType and FunctionProtoType.
2450///
2451class FunctionType : public Type {
2452  // The type returned by the function.
2453  QualType ResultType;
2454
2455 public:
2456  /// ExtInfo - A class which abstracts out some details necessary for
2457  /// making a call.
2458  ///
2459  /// It is not actually used directly for storing this information in
2460  /// a FunctionType, although FunctionType does currently use the
2461  /// same bit-pattern.
2462  ///
2463  // If you add a field (say Foo), other than the obvious places (both,
2464  // constructors, compile failures), what you need to update is
2465  // * Operator==
2466  // * getFoo
2467  // * withFoo
2468  // * functionType. Add Foo, getFoo.
2469  // * ASTContext::getFooType
2470  // * ASTContext::mergeFunctionTypes
2471  // * FunctionNoProtoType::Profile
2472  // * FunctionProtoType::Profile
2473  // * TypePrinter::PrintFunctionProto
2474  // * AST read and write
2475  // * Codegen
2476  class ExtInfo {
2477    // Feel free to rearrange or add bits, but if you go over 8,
2478    // you'll need to adjust both the Bits field below and
2479    // Type::FunctionTypeBitfields.
2480
2481    //   |  CC  |noreturn|produces|regparm|
2482    //   |0 .. 2|   3    |    4   | 5 .. 7|
2483    //
2484    // regparm is either 0 (no regparm attribute) or the regparm value+1.
2485    enum { CallConvMask = 0x7 };
2486    enum { NoReturnMask = 0x8 };
2487    enum { ProducesResultMask = 0x10 };
2488    enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2489           RegParmOffset = 5 }; // Assumed to be the last field
2490
2491    uint16_t Bits;
2492
2493    ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2494
2495    friend class FunctionType;
2496
2497   public:
2498    // Constructor with no defaults. Use this when you know that you
2499    // have all the elements (when reading an AST file for example).
2500    ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2501            bool producesResult) {
2502      assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2503      Bits = ((unsigned) cc) |
2504             (noReturn ? NoReturnMask : 0) |
2505             (producesResult ? ProducesResultMask : 0) |
2506             (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2507    }
2508
2509    // Constructor with all defaults. Use when for example creating a
2510    // function know to use defaults.
2511    ExtInfo() : Bits(0) {}
2512
2513    bool getNoReturn() const { return Bits & NoReturnMask; }
2514    bool getProducesResult() const { return Bits & ProducesResultMask; }
2515    bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2516    unsigned getRegParm() const {
2517      unsigned RegParm = Bits >> RegParmOffset;
2518      if (RegParm > 0)
2519        --RegParm;
2520      return RegParm;
2521    }
2522    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2523
2524    bool operator==(ExtInfo Other) const {
2525      return Bits == Other.Bits;
2526    }
2527    bool operator!=(ExtInfo Other) const {
2528      return Bits != Other.Bits;
2529    }
2530
2531    // Note that we don't have setters. That is by design, use
2532    // the following with methods instead of mutating these objects.
2533
2534    ExtInfo withNoReturn(bool noReturn) const {
2535      if (noReturn)
2536        return ExtInfo(Bits | NoReturnMask);
2537      else
2538        return ExtInfo(Bits & ~NoReturnMask);
2539    }
2540
2541    ExtInfo withProducesResult(bool producesResult) const {
2542      if (producesResult)
2543        return ExtInfo(Bits | ProducesResultMask);
2544      else
2545        return ExtInfo(Bits & ~ProducesResultMask);
2546    }
2547
2548    ExtInfo withRegParm(unsigned RegParm) const {
2549      assert(RegParm < 7 && "Invalid regparm value");
2550      return ExtInfo((Bits & ~RegParmMask) |
2551                     ((RegParm + 1) << RegParmOffset));
2552    }
2553
2554    ExtInfo withCallingConv(CallingConv cc) const {
2555      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2556    }
2557
2558    void Profile(llvm::FoldingSetNodeID &ID) const {
2559      ID.AddInteger(Bits);
2560    }
2561  };
2562
2563protected:
2564  FunctionType(TypeClass tc, QualType res, bool variadic,
2565               unsigned typeQuals, RefQualifierKind RefQualifier,
2566               QualType Canonical, bool Dependent,
2567               bool InstantiationDependent,
2568               bool VariablyModified, bool ContainsUnexpandedParameterPack,
2569               ExtInfo Info)
2570    : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2571           ContainsUnexpandedParameterPack),
2572      ResultType(res) {
2573    FunctionTypeBits.ExtInfo = Info.Bits;
2574    FunctionTypeBits.Variadic = variadic;
2575    FunctionTypeBits.TypeQuals = typeQuals;
2576    FunctionTypeBits.RefQualifier = static_cast<unsigned>(RefQualifier);
2577  }
2578  bool isVariadic() const { return FunctionTypeBits.Variadic; }
2579  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2580
2581  RefQualifierKind getRefQualifier() const {
2582    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
2583  }
2584
2585public:
2586
2587  QualType getResultType() const { return ResultType; }
2588
2589  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2590  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2591  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2592  CallingConv getCallConv() const { return getExtInfo().getCC(); }
2593  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2594
2595  /// \brief Determine the type of an expression that calls a function of
2596  /// this type.
2597  QualType getCallResultType(ASTContext &Context) const {
2598    return getResultType().getNonLValueExprType(Context);
2599  }
2600
2601  static StringRef getNameForCallConv(CallingConv CC);
2602
2603  static bool classof(const Type *T) {
2604    return T->getTypeClass() == FunctionNoProto ||
2605           T->getTypeClass() == FunctionProto;
2606  }
2607  static bool classof(const FunctionType *) { return true; }
2608};
2609
2610/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2611/// no information available about its arguments.
2612class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2613  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2614    : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
2615                   /*Dependent=*/false, /*InstantiationDependent=*/false,
2616                   Result->isVariablyModifiedType(),
2617                   /*ContainsUnexpandedParameterPack=*/false, Info) {}
2618
2619  friend class ASTContext;  // ASTContext creates these.
2620
2621public:
2622  // No additional state past what FunctionType provides.
2623
2624  bool isSugared() const { return false; }
2625  QualType desugar() const { return QualType(this, 0); }
2626
2627  void Profile(llvm::FoldingSetNodeID &ID) {
2628    Profile(ID, getResultType(), getExtInfo());
2629  }
2630  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2631                      ExtInfo Info) {
2632    Info.Profile(ID);
2633    ID.AddPointer(ResultType.getAsOpaquePtr());
2634  }
2635
2636  static bool classof(const Type *T) {
2637    return T->getTypeClass() == FunctionNoProto;
2638  }
2639  static bool classof(const FunctionNoProtoType *) { return true; }
2640};
2641
2642/// FunctionProtoType - Represents a prototype with argument type info, e.g.
2643/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2644/// arguments, not as having a single void argument. Such a type can have an
2645/// exception specification, but this specification is not part of the canonical
2646/// type.
2647class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2648public:
2649  /// ExtProtoInfo - Extra information about a function prototype.
2650  struct ExtProtoInfo {
2651    ExtProtoInfo() :
2652      Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
2653      RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr(0),
2654      ConsumedArguments(0) {}
2655
2656    FunctionType::ExtInfo ExtInfo;
2657    bool Variadic;
2658    ExceptionSpecificationType ExceptionSpecType;
2659    unsigned char TypeQuals;
2660    RefQualifierKind RefQualifier;
2661    unsigned NumExceptions;
2662    const QualType *Exceptions;
2663    Expr *NoexceptExpr;
2664    const bool *ConsumedArguments;
2665  };
2666
2667private:
2668  /// \brief Determine whether there are any argument types that
2669  /// contain an unexpanded parameter pack.
2670  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2671                                                 unsigned numArgs) {
2672    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2673      if (ArgArray[Idx]->containsUnexpandedParameterPack())
2674        return true;
2675
2676    return false;
2677  }
2678
2679  FunctionProtoType(QualType result, const QualType *args, unsigned numArgs,
2680                    QualType canonical, const ExtProtoInfo &epi);
2681
2682  /// NumArgs - The number of arguments this function has, not counting '...'.
2683  unsigned NumArgs : 19;
2684
2685  /// NumExceptions - The number of types in the exception spec, if any.
2686  unsigned NumExceptions : 9;
2687
2688  /// ExceptionSpecType - The type of exception specification this function has.
2689  unsigned ExceptionSpecType : 3;
2690
2691  /// HasAnyConsumedArgs - Whether this function has any consumed arguments.
2692  unsigned HasAnyConsumedArgs : 1;
2693
2694  // ArgInfo - There is an variable size array after the class in memory that
2695  // holds the argument types.
2696
2697  // Exceptions - There is another variable size array after ArgInfo that
2698  // holds the exception types.
2699
2700  // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2701  // to the expression in the noexcept() specifier.
2702
2703  // ConsumedArgs - A variable size array, following Exceptions
2704  // and of length NumArgs, holding flags indicating which arguments
2705  // are consumed.  This only appears if HasAnyConsumedArgs is true.
2706
2707  friend class ASTContext;  // ASTContext creates these.
2708
2709  const bool *getConsumedArgsBuffer() const {
2710    assert(hasAnyConsumedArgs());
2711
2712    // Find the end of the exceptions.
2713    Expr * const *eh_end = reinterpret_cast<Expr * const *>(arg_type_end());
2714    if (getExceptionSpecType() != EST_ComputedNoexcept)
2715      eh_end += NumExceptions;
2716    else
2717      eh_end += 1; // NoexceptExpr
2718
2719    return reinterpret_cast<const bool*>(eh_end);
2720  }
2721
2722public:
2723  unsigned getNumArgs() const { return NumArgs; }
2724  QualType getArgType(unsigned i) const {
2725    assert(i < NumArgs && "Invalid argument number!");
2726    return arg_type_begin()[i];
2727  }
2728
2729  ExtProtoInfo getExtProtoInfo() const {
2730    ExtProtoInfo EPI;
2731    EPI.ExtInfo = getExtInfo();
2732    EPI.Variadic = isVariadic();
2733    EPI.ExceptionSpecType = getExceptionSpecType();
2734    EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2735    EPI.RefQualifier = getRefQualifier();
2736    if (EPI.ExceptionSpecType == EST_Dynamic) {
2737      EPI.NumExceptions = NumExceptions;
2738      EPI.Exceptions = exception_begin();
2739    } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2740      EPI.NoexceptExpr = getNoexceptExpr();
2741    }
2742    if (hasAnyConsumedArgs())
2743      EPI.ConsumedArguments = getConsumedArgsBuffer();
2744    return EPI;
2745  }
2746
2747  /// \brief Get the kind of exception specification on this function.
2748  ExceptionSpecificationType getExceptionSpecType() const {
2749    return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2750  }
2751  /// \brief Return whether this function has any kind of exception spec.
2752  bool hasExceptionSpec() const {
2753    return getExceptionSpecType() != EST_None;
2754  }
2755  /// \brief Return whether this function has a dynamic (throw) exception spec.
2756  bool hasDynamicExceptionSpec() const {
2757    return isDynamicExceptionSpec(getExceptionSpecType());
2758  }
2759  /// \brief Return whether this function has a noexcept exception spec.
2760  bool hasNoexceptExceptionSpec() const {
2761    return isNoexceptExceptionSpec(getExceptionSpecType());
2762  }
2763  /// \brief Result type of getNoexceptSpec().
2764  enum NoexceptResult {
2765    NR_NoNoexcept,  ///< There is no noexcept specifier.
2766    NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2767    NR_Dependent,   ///< The noexcept specifier is dependent.
2768    NR_Throw,       ///< The noexcept specifier evaluates to false.
2769    NR_Nothrow      ///< The noexcept specifier evaluates to true.
2770  };
2771  /// \brief Get the meaning of the noexcept spec on this function, if any.
2772  NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2773  unsigned getNumExceptions() const { return NumExceptions; }
2774  QualType getExceptionType(unsigned i) const {
2775    assert(i < NumExceptions && "Invalid exception number!");
2776    return exception_begin()[i];
2777  }
2778  Expr *getNoexceptExpr() const {
2779    if (getExceptionSpecType() != EST_ComputedNoexcept)
2780      return 0;
2781    // NoexceptExpr sits where the arguments end.
2782    return *reinterpret_cast<Expr *const *>(arg_type_end());
2783  }
2784  bool isNothrow(ASTContext &Ctx) const {
2785    ExceptionSpecificationType EST = getExceptionSpecType();
2786    assert(EST != EST_Delayed);
2787    if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2788      return true;
2789    if (EST != EST_ComputedNoexcept)
2790      return false;
2791    return getNoexceptSpec(Ctx) == NR_Nothrow;
2792  }
2793
2794  using FunctionType::isVariadic;
2795
2796  /// \brief Determines whether this function prototype contains a
2797  /// parameter pack at the end.
2798  ///
2799  /// A function template whose last parameter is a parameter pack can be
2800  /// called with an arbitrary number of arguments, much like a variadic
2801  /// function. However,
2802  bool isTemplateVariadic() const;
2803
2804  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2805
2806
2807  /// \brief Retrieve the ref-qualifier associated with this function type.
2808  RefQualifierKind getRefQualifier() const {
2809    return FunctionType::getRefQualifier();
2810  }
2811
2812  typedef const QualType *arg_type_iterator;
2813  arg_type_iterator arg_type_begin() const {
2814    return reinterpret_cast<const QualType *>(this+1);
2815  }
2816  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2817
2818  typedef const QualType *exception_iterator;
2819  exception_iterator exception_begin() const {
2820    // exceptions begin where arguments end
2821    return arg_type_end();
2822  }
2823  exception_iterator exception_end() const {
2824    if (getExceptionSpecType() != EST_Dynamic)
2825      return exception_begin();
2826    return exception_begin() + NumExceptions;
2827  }
2828
2829  bool hasAnyConsumedArgs() const {
2830    return HasAnyConsumedArgs;
2831  }
2832  bool isArgConsumed(unsigned I) const {
2833    assert(I < getNumArgs() && "argument index out of range!");
2834    if (hasAnyConsumedArgs())
2835      return getConsumedArgsBuffer()[I];
2836    return false;
2837  }
2838
2839  bool isSugared() const { return false; }
2840  QualType desugar() const { return QualType(this, 0); }
2841
2842  static bool classof(const Type *T) {
2843    return T->getTypeClass() == FunctionProto;
2844  }
2845  static bool classof(const FunctionProtoType *) { return true; }
2846
2847  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
2848  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2849                      arg_type_iterator ArgTys, unsigned NumArgs,
2850                      const ExtProtoInfo &EPI, const ASTContext &Context);
2851};
2852
2853
2854/// \brief Represents the dependent type named by a dependently-scoped
2855/// typename using declaration, e.g.
2856///   using typename Base<T>::foo;
2857/// Template instantiation turns these into the underlying type.
2858class UnresolvedUsingType : public Type {
2859  UnresolvedUsingTypenameDecl *Decl;
2860
2861  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2862    : Type(UnresolvedUsing, QualType(), true, true, false,
2863           /*ContainsUnexpandedParameterPack=*/false),
2864      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2865  friend class ASTContext; // ASTContext creates these.
2866public:
2867
2868  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2869
2870  bool isSugared() const { return false; }
2871  QualType desugar() const { return QualType(this, 0); }
2872
2873  static bool classof(const Type *T) {
2874    return T->getTypeClass() == UnresolvedUsing;
2875  }
2876  static bool classof(const UnresolvedUsingType *) { return true; }
2877
2878  void Profile(llvm::FoldingSetNodeID &ID) {
2879    return Profile(ID, Decl);
2880  }
2881  static void Profile(llvm::FoldingSetNodeID &ID,
2882                      UnresolvedUsingTypenameDecl *D) {
2883    ID.AddPointer(D);
2884  }
2885};
2886
2887
2888class TypedefType : public Type {
2889  TypedefNameDecl *Decl;
2890protected:
2891  TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
2892    : Type(tc, can, can->isDependentType(),
2893           can->isInstantiationDependentType(),
2894           can->isVariablyModifiedType(),
2895           /*ContainsUnexpandedParameterPack=*/false),
2896      Decl(const_cast<TypedefNameDecl*>(D)) {
2897    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2898  }
2899  friend class ASTContext;  // ASTContext creates these.
2900public:
2901
2902  TypedefNameDecl *getDecl() const { return Decl; }
2903
2904  bool isSugared() const { return true; }
2905  QualType desugar() const;
2906
2907  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2908  static bool classof(const TypedefType *) { return true; }
2909};
2910
2911/// TypeOfExprType (GCC extension).
2912class TypeOfExprType : public Type {
2913  Expr *TOExpr;
2914
2915protected:
2916  TypeOfExprType(Expr *E, QualType can = QualType());
2917  friend class ASTContext;  // ASTContext creates these.
2918public:
2919  Expr *getUnderlyingExpr() const { return TOExpr; }
2920
2921  /// \brief Remove a single level of sugar.
2922  QualType desugar() const;
2923
2924  /// \brief Returns whether this type directly provides sugar.
2925  bool isSugared() const;
2926
2927  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2928  static bool classof(const TypeOfExprType *) { return true; }
2929};
2930
2931/// \brief Internal representation of canonical, dependent
2932/// typeof(expr) types.
2933///
2934/// This class is used internally by the ASTContext to manage
2935/// canonical, dependent types, only. Clients will only see instances
2936/// of this class via TypeOfExprType nodes.
2937class DependentTypeOfExprType
2938  : public TypeOfExprType, public llvm::FoldingSetNode {
2939  const ASTContext &Context;
2940
2941public:
2942  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2943    : TypeOfExprType(E), Context(Context) { }
2944
2945  void Profile(llvm::FoldingSetNodeID &ID) {
2946    Profile(ID, Context, getUnderlyingExpr());
2947  }
2948
2949  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2950                      Expr *E);
2951};
2952
2953/// TypeOfType (GCC extension).
2954class TypeOfType : public Type {
2955  QualType TOType;
2956  TypeOfType(QualType T, QualType can)
2957    : Type(TypeOf, can, T->isDependentType(),
2958           T->isInstantiationDependentType(),
2959           T->isVariablyModifiedType(),
2960           T->containsUnexpandedParameterPack()),
2961      TOType(T) {
2962    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2963  }
2964  friend class ASTContext;  // ASTContext creates these.
2965public:
2966  QualType getUnderlyingType() const { return TOType; }
2967
2968  /// \brief Remove a single level of sugar.
2969  QualType desugar() const { return getUnderlyingType(); }
2970
2971  /// \brief Returns whether this type directly provides sugar.
2972  bool isSugared() const { return true; }
2973
2974  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2975  static bool classof(const TypeOfType *) { return true; }
2976};
2977
2978/// DecltypeType (C++0x)
2979class DecltypeType : public Type {
2980  Expr *E;
2981
2982  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2983  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2984  // from it.
2985  QualType UnderlyingType;
2986
2987protected:
2988  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2989  friend class ASTContext;  // ASTContext creates these.
2990public:
2991  Expr *getUnderlyingExpr() const { return E; }
2992  QualType getUnderlyingType() const { return UnderlyingType; }
2993
2994  /// \brief Remove a single level of sugar.
2995  QualType desugar() const;
2996
2997  /// \brief Returns whether this type directly provides sugar.
2998  bool isSugared() const;
2999
3000  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3001  static bool classof(const DecltypeType *) { return true; }
3002};
3003
3004/// \brief Internal representation of canonical, dependent
3005/// decltype(expr) types.
3006///
3007/// This class is used internally by the ASTContext to manage
3008/// canonical, dependent types, only. Clients will only see instances
3009/// of this class via DecltypeType nodes.
3010class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3011  const ASTContext &Context;
3012
3013public:
3014  DependentDecltypeType(const ASTContext &Context, Expr *E);
3015
3016  void Profile(llvm::FoldingSetNodeID &ID) {
3017    Profile(ID, Context, getUnderlyingExpr());
3018  }
3019
3020  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3021                      Expr *E);
3022};
3023
3024/// \brief A unary type transform, which is a type constructed from another
3025class UnaryTransformType : public Type {
3026public:
3027  enum UTTKind {
3028    EnumUnderlyingType
3029  };
3030
3031private:
3032  /// The untransformed type.
3033  QualType BaseType;
3034  /// The transformed type if not dependent, otherwise the same as BaseType.
3035  QualType UnderlyingType;
3036
3037  UTTKind UKind;
3038protected:
3039  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3040                     QualType CanonicalTy);
3041  friend class ASTContext;
3042public:
3043  bool isSugared() const { return !isDependentType(); }
3044  QualType desugar() const { return UnderlyingType; }
3045
3046  QualType getUnderlyingType() const { return UnderlyingType; }
3047  QualType getBaseType() const { return BaseType; }
3048
3049  UTTKind getUTTKind() const { return UKind; }
3050
3051  static bool classof(const Type *T) {
3052    return T->getTypeClass() == UnaryTransform;
3053  }
3054  static bool classof(const UnaryTransformType *) { return true; }
3055};
3056
3057class TagType : public Type {
3058  /// Stores the TagDecl associated with this type. The decl may point to any
3059  /// TagDecl that declares the entity.
3060  TagDecl * decl;
3061
3062protected:
3063  TagType(TypeClass TC, const TagDecl *D, QualType can);
3064
3065public:
3066  TagDecl *getDecl() const;
3067
3068  /// @brief Determines whether this type is in the process of being
3069  /// defined.
3070  bool isBeingDefined() const;
3071
3072  static bool classof(const Type *T) {
3073    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3074  }
3075  static bool classof(const TagType *) { return true; }
3076  static bool classof(const RecordType *) { return true; }
3077  static bool classof(const EnumType *) { return true; }
3078};
3079
3080/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3081/// to detect TagType objects of structs/unions/classes.
3082class RecordType : public TagType {
3083protected:
3084  explicit RecordType(const RecordDecl *D)
3085    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3086  explicit RecordType(TypeClass TC, RecordDecl *D)
3087    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3088  friend class ASTContext;   // ASTContext creates these.
3089public:
3090
3091  RecordDecl *getDecl() const {
3092    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3093  }
3094
3095  // FIXME: This predicate is a helper to QualType/Type. It needs to
3096  // recursively check all fields for const-ness. If any field is declared
3097  // const, it needs to return false.
3098  bool hasConstFields() const { return false; }
3099
3100  bool isSugared() const { return false; }
3101  QualType desugar() const { return QualType(this, 0); }
3102
3103  static bool classof(const TagType *T);
3104  static bool classof(const Type *T) {
3105    return isa<TagType>(T) && classof(cast<TagType>(T));
3106  }
3107  static bool classof(const RecordType *) { return true; }
3108};
3109
3110/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3111/// to detect TagType objects of enums.
3112class EnumType : public TagType {
3113  explicit EnumType(const EnumDecl *D)
3114    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3115  friend class ASTContext;   // ASTContext creates these.
3116public:
3117
3118  EnumDecl *getDecl() const {
3119    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3120  }
3121
3122  bool isSugared() const { return false; }
3123  QualType desugar() const { return QualType(this, 0); }
3124
3125  static bool classof(const TagType *T);
3126  static bool classof(const Type *T) {
3127    return isa<TagType>(T) && classof(cast<TagType>(T));
3128  }
3129  static bool classof(const EnumType *) { return true; }
3130};
3131
3132/// AttributedType - An attributed type is a type to which a type
3133/// attribute has been applied.  The "modified type" is the
3134/// fully-sugared type to which the attributed type was applied;
3135/// generally it is not canonically equivalent to the attributed type.
3136/// The "equivalent type" is the minimally-desugared type which the
3137/// type is canonically equivalent to.
3138///
3139/// For example, in the following attributed type:
3140///     int32_t __attribute__((vector_size(16)))
3141///   - the modified type is the TypedefType for int32_t
3142///   - the equivalent type is VectorType(16, int32_t)
3143///   - the canonical type is VectorType(16, int)
3144class AttributedType : public Type, public llvm::FoldingSetNode {
3145public:
3146  // It is really silly to have yet another attribute-kind enum, but
3147  // clang::attr::Kind doesn't currently cover the pure type attrs.
3148  enum Kind {
3149    // Expression operand.
3150    attr_address_space,
3151    attr_regparm,
3152    attr_vector_size,
3153    attr_neon_vector_type,
3154    attr_neon_polyvector_type,
3155
3156    FirstExprOperandKind = attr_address_space,
3157    LastExprOperandKind = attr_neon_polyvector_type,
3158
3159    // Enumerated operand (string or keyword).
3160    attr_objc_gc,
3161    attr_objc_ownership,
3162    attr_pcs,
3163
3164    FirstEnumOperandKind = attr_objc_gc,
3165    LastEnumOperandKind = attr_pcs,
3166
3167    // No operand.
3168    attr_noreturn,
3169    attr_cdecl,
3170    attr_fastcall,
3171    attr_stdcall,
3172    attr_thiscall,
3173    attr_pascal
3174  };
3175
3176private:
3177  QualType ModifiedType;
3178  QualType EquivalentType;
3179
3180  friend class ASTContext; // creates these
3181
3182  AttributedType(QualType canon, Kind attrKind,
3183                 QualType modified, QualType equivalent)
3184    : Type(Attributed, canon, canon->isDependentType(),
3185           canon->isInstantiationDependentType(),
3186           canon->isVariablyModifiedType(),
3187           canon->containsUnexpandedParameterPack()),
3188      ModifiedType(modified), EquivalentType(equivalent) {
3189    AttributedTypeBits.AttrKind = attrKind;
3190  }
3191
3192public:
3193  Kind getAttrKind() const {
3194    return static_cast<Kind>(AttributedTypeBits.AttrKind);
3195  }
3196
3197  QualType getModifiedType() const { return ModifiedType; }
3198  QualType getEquivalentType() const { return EquivalentType; }
3199
3200  bool isSugared() const { return true; }
3201  QualType desugar() const { return getEquivalentType(); }
3202
3203  void Profile(llvm::FoldingSetNodeID &ID) {
3204    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3205  }
3206
3207  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3208                      QualType modified, QualType equivalent) {
3209    ID.AddInteger(attrKind);
3210    ID.AddPointer(modified.getAsOpaquePtr());
3211    ID.AddPointer(equivalent.getAsOpaquePtr());
3212  }
3213
3214  static bool classof(const Type *T) {
3215    return T->getTypeClass() == Attributed;
3216  }
3217  static bool classof(const AttributedType *T) { return true; }
3218};
3219
3220class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3221  // Helper data collector for canonical types.
3222  struct CanonicalTTPTInfo {
3223    unsigned Depth : 15;
3224    unsigned ParameterPack : 1;
3225    unsigned Index : 16;
3226  };
3227
3228  union {
3229    // Info for the canonical type.
3230    CanonicalTTPTInfo CanTTPTInfo;
3231    // Info for the non-canonical type.
3232    TemplateTypeParmDecl *TTPDecl;
3233  };
3234
3235  /// Build a non-canonical type.
3236  TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3237    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3238           /*InstantiationDependent=*/true,
3239           /*VariablyModified=*/false,
3240           Canon->containsUnexpandedParameterPack()),
3241      TTPDecl(TTPDecl) { }
3242
3243  /// Build the canonical type.
3244  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3245    : Type(TemplateTypeParm, QualType(this, 0),
3246           /*Dependent=*/true,
3247           /*InstantiationDependent=*/true,
3248           /*VariablyModified=*/false, PP) {
3249    CanTTPTInfo.Depth = D;
3250    CanTTPTInfo.Index = I;
3251    CanTTPTInfo.ParameterPack = PP;
3252  }
3253
3254  friend class ASTContext;  // ASTContext creates these
3255
3256  const CanonicalTTPTInfo& getCanTTPTInfo() const {
3257    QualType Can = getCanonicalTypeInternal();
3258    return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3259  }
3260
3261public:
3262  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3263  unsigned getIndex() const { return getCanTTPTInfo().Index; }
3264  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3265
3266  TemplateTypeParmDecl *getDecl() const {
3267    return isCanonicalUnqualified() ? 0 : TTPDecl;
3268  }
3269
3270  IdentifierInfo *getIdentifier() const;
3271
3272  bool isSugared() const { return false; }
3273  QualType desugar() const { return QualType(this, 0); }
3274
3275  void Profile(llvm::FoldingSetNodeID &ID) {
3276    Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3277  }
3278
3279  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3280                      unsigned Index, bool ParameterPack,
3281                      TemplateTypeParmDecl *TTPDecl) {
3282    ID.AddInteger(Depth);
3283    ID.AddInteger(Index);
3284    ID.AddBoolean(ParameterPack);
3285    ID.AddPointer(TTPDecl);
3286  }
3287
3288  static bool classof(const Type *T) {
3289    return T->getTypeClass() == TemplateTypeParm;
3290  }
3291  static bool classof(const TemplateTypeParmType *T) { return true; }
3292};
3293
3294/// \brief Represents the result of substituting a type for a template
3295/// type parameter.
3296///
3297/// Within an instantiated template, all template type parameters have
3298/// been replaced with these.  They are used solely to record that a
3299/// type was originally written as a template type parameter;
3300/// therefore they are never canonical.
3301class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3302  // The original type parameter.
3303  const TemplateTypeParmType *Replaced;
3304
3305  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3306    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3307           Canon->isInstantiationDependentType(),
3308           Canon->isVariablyModifiedType(),
3309           Canon->containsUnexpandedParameterPack()),
3310      Replaced(Param) { }
3311
3312  friend class ASTContext;
3313
3314public:
3315  /// Gets the template parameter that was substituted for.
3316  const TemplateTypeParmType *getReplacedParameter() const {
3317    return Replaced;
3318  }
3319
3320  /// Gets the type that was substituted for the template
3321  /// parameter.
3322  QualType getReplacementType() const {
3323    return getCanonicalTypeInternal();
3324  }
3325
3326  bool isSugared() const { return true; }
3327  QualType desugar() const { return getReplacementType(); }
3328
3329  void Profile(llvm::FoldingSetNodeID &ID) {
3330    Profile(ID, getReplacedParameter(), getReplacementType());
3331  }
3332  static void Profile(llvm::FoldingSetNodeID &ID,
3333                      const TemplateTypeParmType *Replaced,
3334                      QualType Replacement) {
3335    ID.AddPointer(Replaced);
3336    ID.AddPointer(Replacement.getAsOpaquePtr());
3337  }
3338
3339  static bool classof(const Type *T) {
3340    return T->getTypeClass() == SubstTemplateTypeParm;
3341  }
3342  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
3343};
3344
3345/// \brief Represents the result of substituting a set of types for a template
3346/// type parameter pack.
3347///
3348/// When a pack expansion in the source code contains multiple parameter packs
3349/// and those parameter packs correspond to different levels of template
3350/// parameter lists, this type node is used to represent a template type
3351/// parameter pack from an outer level, which has already had its argument pack
3352/// substituted but that still lives within a pack expansion that itself
3353/// could not be instantiated. When actually performing a substitution into
3354/// that pack expansion (e.g., when all template parameters have corresponding
3355/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3356/// at the current pack substitution index.
3357class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3358  /// \brief The original type parameter.
3359  const TemplateTypeParmType *Replaced;
3360
3361  /// \brief A pointer to the set of template arguments that this
3362  /// parameter pack is instantiated with.
3363  const TemplateArgument *Arguments;
3364
3365  /// \brief The number of template arguments in \c Arguments.
3366  unsigned NumArguments;
3367
3368  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3369                                QualType Canon,
3370                                const TemplateArgument &ArgPack);
3371
3372  friend class ASTContext;
3373
3374public:
3375  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3376
3377  /// Gets the template parameter that was substituted for.
3378  const TemplateTypeParmType *getReplacedParameter() const {
3379    return Replaced;
3380  }
3381
3382  bool isSugared() const { return false; }
3383  QualType desugar() const { return QualType(this, 0); }
3384
3385  TemplateArgument getArgumentPack() const;
3386
3387  void Profile(llvm::FoldingSetNodeID &ID);
3388  static void Profile(llvm::FoldingSetNodeID &ID,
3389                      const TemplateTypeParmType *Replaced,
3390                      const TemplateArgument &ArgPack);
3391
3392  static bool classof(const Type *T) {
3393    return T->getTypeClass() == SubstTemplateTypeParmPack;
3394  }
3395  static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3396};
3397
3398/// \brief Represents a C++0x auto type.
3399///
3400/// These types are usually a placeholder for a deduced type. However, within
3401/// templates and before the initializer is attached, there is no deduced type
3402/// and an auto type is type-dependent and canonical.
3403class AutoType : public Type, public llvm::FoldingSetNode {
3404  AutoType(QualType DeducedType)
3405    : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3406           /*Dependent=*/DeducedType.isNull(),
3407           /*InstantiationDependent=*/DeducedType.isNull(),
3408           /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3409    assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3410           "deduced a dependent type for auto");
3411  }
3412
3413  friend class ASTContext;  // ASTContext creates these
3414
3415public:
3416  bool isSugared() const { return isDeduced(); }
3417  QualType desugar() const { return getCanonicalTypeInternal(); }
3418
3419  QualType getDeducedType() const {
3420    return isDeduced() ? getCanonicalTypeInternal() : QualType();
3421  }
3422  bool isDeduced() const {
3423    return !isDependentType();
3424  }
3425
3426  void Profile(llvm::FoldingSetNodeID &ID) {
3427    Profile(ID, getDeducedType());
3428  }
3429
3430  static void Profile(llvm::FoldingSetNodeID &ID,
3431                      QualType Deduced) {
3432    ID.AddPointer(Deduced.getAsOpaquePtr());
3433  }
3434
3435  static bool classof(const Type *T) {
3436    return T->getTypeClass() == Auto;
3437  }
3438  static bool classof(const AutoType *T) { return true; }
3439};
3440
3441/// \brief Represents a type template specialization; the template
3442/// must be a class template, a type alias template, or a template
3443/// template parameter.  A template which cannot be resolved to one of
3444/// these, e.g. because it is written with a dependent scope
3445/// specifier, is instead represented as a
3446/// @c DependentTemplateSpecializationType.
3447///
3448/// A non-dependent template specialization type is always "sugar",
3449/// typically for a @c RecordType.  For example, a class template
3450/// specialization type of @c vector<int> will refer to a tag type for
3451/// the instantiation @c std::vector<int, std::allocator<int>>
3452///
3453/// Template specializations are dependent if either the template or
3454/// any of the template arguments are dependent, in which case the
3455/// type may also be canonical.
3456///
3457/// Instances of this type are allocated with a trailing array of
3458/// TemplateArguments, followed by a QualType representing the
3459/// non-canonical aliased type when the template is a type alias
3460/// template.
3461class TemplateSpecializationType
3462  : public Type, public llvm::FoldingSetNode {
3463  /// \brief The name of the template being specialized.  This is
3464  /// either a TemplateName::Template (in which case it is a
3465  /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3466  /// TypeAliasTemplateDecl*), a
3467  /// TemplateName::SubstTemplateTemplateParmPack, or a
3468  /// TemplateName::SubstTemplateTemplateParm (in which case the
3469  /// replacement must, recursively, be one of these).
3470  TemplateName Template;
3471
3472  /// \brief - The number of template arguments named in this class
3473  /// template specialization.
3474  unsigned NumArgs;
3475
3476  TemplateSpecializationType(TemplateName T,
3477                             const TemplateArgument *Args,
3478                             unsigned NumArgs, QualType Canon,
3479                             QualType Aliased);
3480
3481  friend class ASTContext;  // ASTContext creates these
3482
3483public:
3484  /// \brief Determine whether any of the given template arguments are
3485  /// dependent.
3486  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3487                                            unsigned NumArgs,
3488                                            bool &InstantiationDependent);
3489
3490  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3491                                            unsigned NumArgs,
3492                                            bool &InstantiationDependent);
3493
3494  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3495                                            bool &InstantiationDependent);
3496
3497  /// \brief Print a template argument list, including the '<' and '>'
3498  /// enclosing the template arguments.
3499  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3500                                               unsigned NumArgs,
3501                                               const PrintingPolicy &Policy,
3502                                               bool SkipBrackets = false);
3503
3504  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3505                                               unsigned NumArgs,
3506                                               const PrintingPolicy &Policy);
3507
3508  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3509                                               const PrintingPolicy &Policy);
3510
3511  /// True if this template specialization type matches a current
3512  /// instantiation in the context in which it is found.
3513  bool isCurrentInstantiation() const {
3514    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3515  }
3516
3517  /// True if this template specialization type is for a type alias
3518  /// template.
3519  bool isTypeAlias() const;
3520  /// Get the aliased type, if this is a specialization of a type alias
3521  /// template.
3522  QualType getAliasedType() const {
3523    assert(isTypeAlias() && "not a type alias template specialization");
3524    return *reinterpret_cast<const QualType*>(end());
3525  }
3526
3527  typedef const TemplateArgument * iterator;
3528
3529  iterator begin() const { return getArgs(); }
3530  iterator end() const; // defined inline in TemplateBase.h
3531
3532  /// \brief Retrieve the name of the template that we are specializing.
3533  TemplateName getTemplateName() const { return Template; }
3534
3535  /// \brief Retrieve the template arguments.
3536  const TemplateArgument *getArgs() const {
3537    return reinterpret_cast<const TemplateArgument *>(this + 1);
3538  }
3539
3540  /// \brief Retrieve the number of template arguments.
3541  unsigned getNumArgs() const { return NumArgs; }
3542
3543  /// \brief Retrieve a specific template argument as a type.
3544  /// \precondition @c isArgType(Arg)
3545  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3546
3547  bool isSugared() const {
3548    return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3549  }
3550  QualType desugar() const { return getCanonicalTypeInternal(); }
3551
3552  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3553    Profile(ID, Template, getArgs(), NumArgs, Ctx);
3554    if (isTypeAlias())
3555      getAliasedType().Profile(ID);
3556  }
3557
3558  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3559                      const TemplateArgument *Args,
3560                      unsigned NumArgs,
3561                      const ASTContext &Context);
3562
3563  static bool classof(const Type *T) {
3564    return T->getTypeClass() == TemplateSpecialization;
3565  }
3566  static bool classof(const TemplateSpecializationType *T) { return true; }
3567};
3568
3569/// \brief The injected class name of a C++ class template or class
3570/// template partial specialization.  Used to record that a type was
3571/// spelled with a bare identifier rather than as a template-id; the
3572/// equivalent for non-templated classes is just RecordType.
3573///
3574/// Injected class name types are always dependent.  Template
3575/// instantiation turns these into RecordTypes.
3576///
3577/// Injected class name types are always canonical.  This works
3578/// because it is impossible to compare an injected class name type
3579/// with the corresponding non-injected template type, for the same
3580/// reason that it is impossible to directly compare template
3581/// parameters from different dependent contexts: injected class name
3582/// types can only occur within the scope of a particular templated
3583/// declaration, and within that scope every template specialization
3584/// will canonicalize to the injected class name (when appropriate
3585/// according to the rules of the language).
3586class InjectedClassNameType : public Type {
3587  CXXRecordDecl *Decl;
3588
3589  /// The template specialization which this type represents.
3590  /// For example, in
3591  ///   template <class T> class A { ... };
3592  /// this is A<T>, whereas in
3593  ///   template <class X, class Y> class A<B<X,Y> > { ... };
3594  /// this is A<B<X,Y> >.
3595  ///
3596  /// It is always unqualified, always a template specialization type,
3597  /// and always dependent.
3598  QualType InjectedType;
3599
3600  friend class ASTContext; // ASTContext creates these.
3601  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3602                          // currently suitable for AST reading, too much
3603                          // interdependencies.
3604  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3605    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3606           /*InstantiationDependent=*/true,
3607           /*VariablyModified=*/false,
3608           /*ContainsUnexpandedParameterPack=*/false),
3609      Decl(D), InjectedType(TST) {
3610    assert(isa<TemplateSpecializationType>(TST));
3611    assert(!TST.hasQualifiers());
3612    assert(TST->isDependentType());
3613  }
3614
3615public:
3616  QualType getInjectedSpecializationType() const { return InjectedType; }
3617  const TemplateSpecializationType *getInjectedTST() const {
3618    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3619  }
3620
3621  CXXRecordDecl *getDecl() const;
3622
3623  bool isSugared() const { return false; }
3624  QualType desugar() const { return QualType(this, 0); }
3625
3626  static bool classof(const Type *T) {
3627    return T->getTypeClass() == InjectedClassName;
3628  }
3629  static bool classof(const InjectedClassNameType *T) { return true; }
3630};
3631
3632/// \brief The kind of a tag type.
3633enum TagTypeKind {
3634  /// \brief The "struct" keyword.
3635  TTK_Struct,
3636  /// \brief The "union" keyword.
3637  TTK_Union,
3638  /// \brief The "class" keyword.
3639  TTK_Class,
3640  /// \brief The "enum" keyword.
3641  TTK_Enum
3642};
3643
3644/// \brief The elaboration keyword that precedes a qualified type name or
3645/// introduces an elaborated-type-specifier.
3646enum ElaboratedTypeKeyword {
3647  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3648  ETK_Struct,
3649  /// \brief The "union" keyword introduces the elaborated-type-specifier.
3650  ETK_Union,
3651  /// \brief The "class" keyword introduces the elaborated-type-specifier.
3652  ETK_Class,
3653  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3654  ETK_Enum,
3655  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3656  /// \c typename T::type.
3657  ETK_Typename,
3658  /// \brief No keyword precedes the qualified type name.
3659  ETK_None
3660};
3661
3662/// A helper class for Type nodes having an ElaboratedTypeKeyword.
3663/// The keyword in stored in the free bits of the base class.
3664/// Also provides a few static helpers for converting and printing
3665/// elaborated type keyword and tag type kind enumerations.
3666class TypeWithKeyword : public Type {
3667protected:
3668  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3669                  QualType Canonical, bool Dependent,
3670                  bool InstantiationDependent, bool VariablyModified,
3671                  bool ContainsUnexpandedParameterPack)
3672  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3673         ContainsUnexpandedParameterPack) {
3674    TypeWithKeywordBits.Keyword = Keyword;
3675  }
3676
3677public:
3678  ElaboratedTypeKeyword getKeyword() const {
3679    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3680  }
3681
3682  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3683  /// into an elaborated type keyword.
3684  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3685
3686  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3687  /// into a tag type kind.  It is an error to provide a type specifier
3688  /// which *isn't* a tag kind here.
3689  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3690
3691  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3692  /// elaborated type keyword.
3693  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3694
3695  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3696  // a TagTypeKind. It is an error to provide an elaborated type keyword
3697  /// which *isn't* a tag kind here.
3698  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3699
3700  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3701
3702  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3703
3704  static const char *getTagTypeKindName(TagTypeKind Kind) {
3705    return getKeywordName(getKeywordForTagTypeKind(Kind));
3706  }
3707
3708  class CannotCastToThisType {};
3709  static CannotCastToThisType classof(const Type *);
3710};
3711
3712/// \brief Represents a type that was referred to using an elaborated type
3713/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3714/// or both.
3715///
3716/// This type is used to keep track of a type name as written in the
3717/// source code, including tag keywords and any nested-name-specifiers.
3718/// The type itself is always "sugar", used to express what was written
3719/// in the source code but containing no additional semantic information.
3720class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3721
3722  /// \brief The nested name specifier containing the qualifier.
3723  NestedNameSpecifier *NNS;
3724
3725  /// \brief The type that this qualified name refers to.
3726  QualType NamedType;
3727
3728  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3729                 QualType NamedType, QualType CanonType)
3730    : TypeWithKeyword(Keyword, Elaborated, CanonType,
3731                      NamedType->isDependentType(),
3732                      NamedType->isInstantiationDependentType(),
3733                      NamedType->isVariablyModifiedType(),
3734                      NamedType->containsUnexpandedParameterPack()),
3735      NNS(NNS), NamedType(NamedType) {
3736    assert(!(Keyword == ETK_None && NNS == 0) &&
3737           "ElaboratedType cannot have elaborated type keyword "
3738           "and name qualifier both null.");
3739  }
3740
3741  friend class ASTContext;  // ASTContext creates these
3742
3743public:
3744  ~ElaboratedType();
3745
3746  /// \brief Retrieve the qualification on this type.
3747  NestedNameSpecifier *getQualifier() const { return NNS; }
3748
3749  /// \brief Retrieve the type named by the qualified-id.
3750  QualType getNamedType() const { return NamedType; }
3751
3752  /// \brief Remove a single level of sugar.
3753  QualType desugar() const { return getNamedType(); }
3754
3755  /// \brief Returns whether this type directly provides sugar.
3756  bool isSugared() const { return true; }
3757
3758  void Profile(llvm::FoldingSetNodeID &ID) {
3759    Profile(ID, getKeyword(), NNS, NamedType);
3760  }
3761
3762  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3763                      NestedNameSpecifier *NNS, QualType NamedType) {
3764    ID.AddInteger(Keyword);
3765    ID.AddPointer(NNS);
3766    NamedType.Profile(ID);
3767  }
3768
3769  static bool classof(const Type *T) {
3770    return T->getTypeClass() == Elaborated;
3771  }
3772  static bool classof(const ElaboratedType *T) { return true; }
3773};
3774
3775/// \brief Represents a qualified type name for which the type name is
3776/// dependent.
3777///
3778/// DependentNameType represents a class of dependent types that involve a
3779/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3780/// name of a type. The DependentNameType may start with a "typename" (for a
3781/// typename-specifier), "class", "struct", "union", or "enum" (for a
3782/// dependent elaborated-type-specifier), or nothing (in contexts where we
3783/// know that we must be referring to a type, e.g., in a base class specifier).
3784class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3785
3786  /// \brief The nested name specifier containing the qualifier.
3787  NestedNameSpecifier *NNS;
3788
3789  /// \brief The type that this typename specifier refers to.
3790  const IdentifierInfo *Name;
3791
3792  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3793                    const IdentifierInfo *Name, QualType CanonType)
3794    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3795                      /*InstantiationDependent=*/true,
3796                      /*VariablyModified=*/false,
3797                      NNS->containsUnexpandedParameterPack()),
3798      NNS(NNS), Name(Name) {
3799    assert(NNS->isDependent() &&
3800           "DependentNameType requires a dependent nested-name-specifier");
3801  }
3802
3803  friend class ASTContext;  // ASTContext creates these
3804
3805public:
3806  /// \brief Retrieve the qualification on this type.
3807  NestedNameSpecifier *getQualifier() const { return NNS; }
3808
3809  /// \brief Retrieve the type named by the typename specifier as an
3810  /// identifier.
3811  ///
3812  /// This routine will return a non-NULL identifier pointer when the
3813  /// form of the original typename was terminated by an identifier,
3814  /// e.g., "typename T::type".
3815  const IdentifierInfo *getIdentifier() const {
3816    return Name;
3817  }
3818
3819  bool isSugared() const { return false; }
3820  QualType desugar() const { return QualType(this, 0); }
3821
3822  void Profile(llvm::FoldingSetNodeID &ID) {
3823    Profile(ID, getKeyword(), NNS, Name);
3824  }
3825
3826  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3827                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3828    ID.AddInteger(Keyword);
3829    ID.AddPointer(NNS);
3830    ID.AddPointer(Name);
3831  }
3832
3833  static bool classof(const Type *T) {
3834    return T->getTypeClass() == DependentName;
3835  }
3836  static bool classof(const DependentNameType *T) { return true; }
3837};
3838
3839/// DependentTemplateSpecializationType - Represents a template
3840/// specialization type whose template cannot be resolved, e.g.
3841///   A<T>::template B<T>
3842class DependentTemplateSpecializationType :
3843  public TypeWithKeyword, public llvm::FoldingSetNode {
3844
3845  /// \brief The nested name specifier containing the qualifier.
3846  NestedNameSpecifier *NNS;
3847
3848  /// \brief The identifier of the template.
3849  const IdentifierInfo *Name;
3850
3851  /// \brief - The number of template arguments named in this class
3852  /// template specialization.
3853  unsigned NumArgs;
3854
3855  const TemplateArgument *getArgBuffer() const {
3856    return reinterpret_cast<const TemplateArgument*>(this+1);
3857  }
3858  TemplateArgument *getArgBuffer() {
3859    return reinterpret_cast<TemplateArgument*>(this+1);
3860  }
3861
3862  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3863                                      NestedNameSpecifier *NNS,
3864                                      const IdentifierInfo *Name,
3865                                      unsigned NumArgs,
3866                                      const TemplateArgument *Args,
3867                                      QualType Canon);
3868
3869  friend class ASTContext;  // ASTContext creates these
3870
3871public:
3872  NestedNameSpecifier *getQualifier() const { return NNS; }
3873  const IdentifierInfo *getIdentifier() const { return Name; }
3874
3875  /// \brief Retrieve the template arguments.
3876  const TemplateArgument *getArgs() const {
3877    return getArgBuffer();
3878  }
3879
3880  /// \brief Retrieve the number of template arguments.
3881  unsigned getNumArgs() const { return NumArgs; }
3882
3883  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3884
3885  typedef const TemplateArgument * iterator;
3886  iterator begin() const { return getArgs(); }
3887  iterator end() const; // inline in TemplateBase.h
3888
3889  bool isSugared() const { return false; }
3890  QualType desugar() const { return QualType(this, 0); }
3891
3892  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3893    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3894  }
3895
3896  static void Profile(llvm::FoldingSetNodeID &ID,
3897                      const ASTContext &Context,
3898                      ElaboratedTypeKeyword Keyword,
3899                      NestedNameSpecifier *Qualifier,
3900                      const IdentifierInfo *Name,
3901                      unsigned NumArgs,
3902                      const TemplateArgument *Args);
3903
3904  static bool classof(const Type *T) {
3905    return T->getTypeClass() == DependentTemplateSpecialization;
3906  }
3907  static bool classof(const DependentTemplateSpecializationType *T) {
3908    return true;
3909  }
3910};
3911
3912/// \brief Represents a pack expansion of types.
3913///
3914/// Pack expansions are part of C++0x variadic templates. A pack
3915/// expansion contains a pattern, which itself contains one or more
3916/// "unexpanded" parameter packs. When instantiated, a pack expansion
3917/// produces a series of types, each instantiated from the pattern of
3918/// the expansion, where the Ith instantiation of the pattern uses the
3919/// Ith arguments bound to each of the unexpanded parameter packs. The
3920/// pack expansion is considered to "expand" these unexpanded
3921/// parameter packs.
3922///
3923/// \code
3924/// template<typename ...Types> struct tuple;
3925///
3926/// template<typename ...Types>
3927/// struct tuple_of_references {
3928///   typedef tuple<Types&...> type;
3929/// };
3930/// \endcode
3931///
3932/// Here, the pack expansion \c Types&... is represented via a
3933/// PackExpansionType whose pattern is Types&.
3934class PackExpansionType : public Type, public llvm::FoldingSetNode {
3935  /// \brief The pattern of the pack expansion.
3936  QualType Pattern;
3937
3938  /// \brief The number of expansions that this pack expansion will
3939  /// generate when substituted (+1), or indicates that
3940  ///
3941  /// This field will only have a non-zero value when some of the parameter
3942  /// packs that occur within the pattern have been substituted but others have
3943  /// not.
3944  unsigned NumExpansions;
3945
3946  PackExpansionType(QualType Pattern, QualType Canon,
3947                    llvm::Optional<unsigned> NumExpansions)
3948    : Type(PackExpansion, Canon, /*Dependent=*/true,
3949           /*InstantiationDependent=*/true,
3950           /*VariableModified=*/Pattern->isVariablyModifiedType(),
3951           /*ContainsUnexpandedParameterPack=*/false),
3952      Pattern(Pattern),
3953      NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3954
3955  friend class ASTContext;  // ASTContext creates these
3956
3957public:
3958  /// \brief Retrieve the pattern of this pack expansion, which is the
3959  /// type that will be repeatedly instantiated when instantiating the
3960  /// pack expansion itself.
3961  QualType getPattern() const { return Pattern; }
3962
3963  /// \brief Retrieve the number of expansions that this pack expansion will
3964  /// generate, if known.
3965  llvm::Optional<unsigned> getNumExpansions() const {
3966    if (NumExpansions)
3967      return NumExpansions - 1;
3968
3969    return llvm::Optional<unsigned>();
3970  }
3971
3972  bool isSugared() const { return false; }
3973  QualType desugar() const { return QualType(this, 0); }
3974
3975  void Profile(llvm::FoldingSetNodeID &ID) {
3976    Profile(ID, getPattern(), getNumExpansions());
3977  }
3978
3979  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
3980                      llvm::Optional<unsigned> NumExpansions) {
3981    ID.AddPointer(Pattern.getAsOpaquePtr());
3982    ID.AddBoolean(NumExpansions);
3983    if (NumExpansions)
3984      ID.AddInteger(*NumExpansions);
3985  }
3986
3987  static bool classof(const Type *T) {
3988    return T->getTypeClass() == PackExpansion;
3989  }
3990  static bool classof(const PackExpansionType *T) {
3991    return true;
3992  }
3993};
3994
3995/// ObjCObjectType - Represents a class type in Objective C.
3996/// Every Objective C type is a combination of a base type and a
3997/// list of protocols.
3998///
3999/// Given the following declarations:
4000///   @class C;
4001///   @protocol P;
4002///
4003/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
4004/// with base C and no protocols.
4005///
4006/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4007///
4008/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
4009/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4010/// and no protocols.
4011///
4012/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
4013/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
4014/// this should get its own sugar class to better represent the source.
4015class ObjCObjectType : public Type {
4016  // ObjCObjectType.NumProtocols - the number of protocols stored
4017  // after the ObjCObjectPointerType node.
4018  //
4019  // These protocols are those written directly on the type.  If
4020  // protocol qualifiers ever become additive, the iterators will need
4021  // to get kindof complicated.
4022  //
4023  // In the canonical object type, these are sorted alphabetically
4024  // and uniqued.
4025
4026  /// Either a BuiltinType or an InterfaceType or sugar for either.
4027  QualType BaseType;
4028
4029  ObjCProtocolDecl * const *getProtocolStorage() const {
4030    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4031  }
4032
4033  ObjCProtocolDecl **getProtocolStorage();
4034
4035protected:
4036  ObjCObjectType(QualType Canonical, QualType Base,
4037                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4038
4039  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4040  ObjCObjectType(enum Nonce_ObjCInterface)
4041        : Type(ObjCInterface, QualType(), false, false, false, false),
4042      BaseType(QualType(this_(), 0)) {
4043    ObjCObjectTypeBits.NumProtocols = 0;
4044  }
4045
4046public:
4047  /// getBaseType - Gets the base type of this object type.  This is
4048  /// always (possibly sugar for) one of:
4049  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
4050  ///    user, which is a typedef for an ObjCPointerType)
4051  ///  - the 'Class' builtin type (same caveat)
4052  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
4053  QualType getBaseType() const { return BaseType; }
4054
4055  bool isObjCId() const {
4056    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4057  }
4058  bool isObjCClass() const {
4059    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4060  }
4061  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4062  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4063  bool isObjCUnqualifiedIdOrClass() const {
4064    if (!qual_empty()) return false;
4065    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4066      return T->getKind() == BuiltinType::ObjCId ||
4067             T->getKind() == BuiltinType::ObjCClass;
4068    return false;
4069  }
4070  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4071  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4072
4073  /// Gets the interface declaration for this object type, if the base type
4074  /// really is an interface.
4075  ObjCInterfaceDecl *getInterface() const;
4076
4077  typedef ObjCProtocolDecl * const *qual_iterator;
4078
4079  qual_iterator qual_begin() const { return getProtocolStorage(); }
4080  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4081
4082  bool qual_empty() const { return getNumProtocols() == 0; }
4083
4084  /// getNumProtocols - Return the number of qualifying protocols in this
4085  /// interface type, or 0 if there are none.
4086  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4087
4088  /// \brief Fetch a protocol by index.
4089  ObjCProtocolDecl *getProtocol(unsigned I) const {
4090    assert(I < getNumProtocols() && "Out-of-range protocol access");
4091    return qual_begin()[I];
4092  }
4093
4094  bool isSugared() const { return false; }
4095  QualType desugar() const { return QualType(this, 0); }
4096
4097  static bool classof(const Type *T) {
4098    return T->getTypeClass() == ObjCObject ||
4099           T->getTypeClass() == ObjCInterface;
4100  }
4101  static bool classof(const ObjCObjectType *) { return true; }
4102};
4103
4104/// ObjCObjectTypeImpl - A class providing a concrete implementation
4105/// of ObjCObjectType, so as to not increase the footprint of
4106/// ObjCInterfaceType.  Code outside of ASTContext and the core type
4107/// system should not reference this type.
4108class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4109  friend class ASTContext;
4110
4111  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4112  // will need to be modified.
4113
4114  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4115                     ObjCProtocolDecl * const *Protocols,
4116                     unsigned NumProtocols)
4117    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4118
4119public:
4120  void Profile(llvm::FoldingSetNodeID &ID);
4121  static void Profile(llvm::FoldingSetNodeID &ID,
4122                      QualType Base,
4123                      ObjCProtocolDecl *const *protocols,
4124                      unsigned NumProtocols);
4125};
4126
4127inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4128  return reinterpret_cast<ObjCProtocolDecl**>(
4129            static_cast<ObjCObjectTypeImpl*>(this) + 1);
4130}
4131
4132/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4133/// object oriented design.  They basically correspond to C++ classes.  There
4134/// are two kinds of interface types, normal interfaces like "NSString" and
4135/// qualified interfaces, which are qualified with a protocol list like
4136/// "NSString<NSCopyable, NSAmazing>".
4137///
4138/// ObjCInterfaceType guarantees the following properties when considered
4139/// as a subtype of its superclass, ObjCObjectType:
4140///   - There are no protocol qualifiers.  To reinforce this, code which
4141///     tries to invoke the protocol methods via an ObjCInterfaceType will
4142///     fail to compile.
4143///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
4144///     T->getBaseType() == QualType(T, 0).
4145class ObjCInterfaceType : public ObjCObjectType {
4146  mutable ObjCInterfaceDecl *Decl;
4147
4148  ObjCInterfaceType(const ObjCInterfaceDecl *D)
4149    : ObjCObjectType(Nonce_ObjCInterface),
4150      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4151  friend class ASTContext;  // ASTContext creates these.
4152  friend class ObjCInterfaceDecl;
4153
4154public:
4155  /// getDecl - Get the declaration of this interface.
4156  ObjCInterfaceDecl *getDecl() const { return Decl; }
4157
4158  bool isSugared() const { return false; }
4159  QualType desugar() const { return QualType(this, 0); }
4160
4161  static bool classof(const Type *T) {
4162    return T->getTypeClass() == ObjCInterface;
4163  }
4164  static bool classof(const ObjCInterfaceType *) { return true; }
4165
4166  // Nonsense to "hide" certain members of ObjCObjectType within this
4167  // class.  People asking for protocols on an ObjCInterfaceType are
4168  // not going to get what they want: ObjCInterfaceTypes are
4169  // guaranteed to have no protocols.
4170  enum {
4171    qual_iterator,
4172    qual_begin,
4173    qual_end,
4174    getNumProtocols,
4175    getProtocol
4176  };
4177};
4178
4179inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4180  if (const ObjCInterfaceType *T =
4181        getBaseType()->getAs<ObjCInterfaceType>())
4182    return T->getDecl();
4183  return 0;
4184}
4185
4186/// ObjCObjectPointerType - Used to represent a pointer to an
4187/// Objective C object.  These are constructed from pointer
4188/// declarators when the pointee type is an ObjCObjectType (or sugar
4189/// for one).  In addition, the 'id' and 'Class' types are typedefs
4190/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4191/// are translated into these.
4192///
4193/// Pointers to pointers to Objective C objects are still PointerTypes;
4194/// only the first level of pointer gets it own type implementation.
4195class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4196  QualType PointeeType;
4197
4198  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4199    : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4200      PointeeType(Pointee) {}
4201  friend class ASTContext;  // ASTContext creates these.
4202
4203public:
4204  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4205  /// The result will always be an ObjCObjectType or sugar thereof.
4206  QualType getPointeeType() const { return PointeeType; }
4207
4208  /// getObjCObjectType - Gets the type pointed to by this ObjC
4209  /// pointer.  This method always returns non-null.
4210  ///
4211  /// This method is equivalent to getPointeeType() except that
4212  /// it discards any typedefs (or other sugar) between this
4213  /// type and the "outermost" object type.  So for:
4214  ///   @class A; @protocol P; @protocol Q;
4215  ///   typedef A<P> AP;
4216  ///   typedef A A1;
4217  ///   typedef A1<P> A1P;
4218  ///   typedef A1P<Q> A1PQ;
4219  /// For 'A*', getObjectType() will return 'A'.
4220  /// For 'A<P>*', getObjectType() will return 'A<P>'.
4221  /// For 'AP*', getObjectType() will return 'A<P>'.
4222  /// For 'A1*', getObjectType() will return 'A'.
4223  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4224  /// For 'A1P*', getObjectType() will return 'A1<P>'.
4225  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4226  ///   adding protocols to a protocol-qualified base discards the
4227  ///   old qualifiers (for now).  But if it didn't, getObjectType()
4228  ///   would return 'A1P<Q>' (and we'd have to make iterating over
4229  ///   qualifiers more complicated).
4230  const ObjCObjectType *getObjectType() const {
4231    return PointeeType->castAs<ObjCObjectType>();
4232  }
4233
4234  /// getInterfaceType - If this pointer points to an Objective C
4235  /// @interface type, gets the type for that interface.  Any protocol
4236  /// qualifiers on the interface are ignored.
4237  ///
4238  /// \return null if the base type for this pointer is 'id' or 'Class'
4239  const ObjCInterfaceType *getInterfaceType() const {
4240    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4241  }
4242
4243  /// getInterfaceDecl - If this pointer points to an Objective @interface
4244  /// type, gets the declaration for that interface.
4245  ///
4246  /// \return null if the base type for this pointer is 'id' or 'Class'
4247  ObjCInterfaceDecl *getInterfaceDecl() const {
4248    return getObjectType()->getInterface();
4249  }
4250
4251  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4252  /// its object type is the primitive 'id' type with no protocols.
4253  bool isObjCIdType() const {
4254    return getObjectType()->isObjCUnqualifiedId();
4255  }
4256
4257  /// isObjCClassType - True if this is equivalent to the 'Class' type,
4258  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4259  bool isObjCClassType() const {
4260    return getObjectType()->isObjCUnqualifiedClass();
4261  }
4262
4263  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4264  /// non-empty set of protocols.
4265  bool isObjCQualifiedIdType() const {
4266    return getObjectType()->isObjCQualifiedId();
4267  }
4268
4269  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4270  /// some non-empty set of protocols.
4271  bool isObjCQualifiedClassType() const {
4272    return getObjectType()->isObjCQualifiedClass();
4273  }
4274
4275  /// An iterator over the qualifiers on the object type.  Provided
4276  /// for convenience.  This will always iterate over the full set of
4277  /// protocols on a type, not just those provided directly.
4278  typedef ObjCObjectType::qual_iterator qual_iterator;
4279
4280  qual_iterator qual_begin() const {
4281    return getObjectType()->qual_begin();
4282  }
4283  qual_iterator qual_end() const {
4284    return getObjectType()->qual_end();
4285  }
4286  bool qual_empty() const { return getObjectType()->qual_empty(); }
4287
4288  /// getNumProtocols - Return the number of qualifying protocols on
4289  /// the object type.
4290  unsigned getNumProtocols() const {
4291    return getObjectType()->getNumProtocols();
4292  }
4293
4294  /// \brief Retrieve a qualifying protocol by index on the object
4295  /// type.
4296  ObjCProtocolDecl *getProtocol(unsigned I) const {
4297    return getObjectType()->getProtocol(I);
4298  }
4299
4300  bool isSugared() const { return false; }
4301  QualType desugar() const { return QualType(this, 0); }
4302
4303  void Profile(llvm::FoldingSetNodeID &ID) {
4304    Profile(ID, getPointeeType());
4305  }
4306  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4307    ID.AddPointer(T.getAsOpaquePtr());
4308  }
4309  static bool classof(const Type *T) {
4310    return T->getTypeClass() == ObjCObjectPointer;
4311  }
4312  static bool classof(const ObjCObjectPointerType *) { return true; }
4313};
4314
4315class AtomicType : public Type, public llvm::FoldingSetNode {
4316  QualType ValueType;
4317
4318  AtomicType(QualType ValTy, QualType Canonical)
4319    : Type(Atomic, Canonical, ValTy->isDependentType(),
4320           ValTy->isInstantiationDependentType(),
4321           ValTy->isVariablyModifiedType(),
4322           ValTy->containsUnexpandedParameterPack()),
4323      ValueType(ValTy) {}
4324  friend class ASTContext;  // ASTContext creates these.
4325
4326  public:
4327  /// getValueType - Gets the type contained by this atomic type, i.e.
4328  /// the type returned by performing an atomic load of this atomic type.
4329  QualType getValueType() const { return ValueType; }
4330
4331  bool isSugared() const { return false; }
4332  QualType desugar() const { return QualType(this, 0); }
4333
4334  void Profile(llvm::FoldingSetNodeID &ID) {
4335    Profile(ID, getValueType());
4336  }
4337  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4338    ID.AddPointer(T.getAsOpaquePtr());
4339  }
4340  static bool classof(const Type *T) {
4341    return T->getTypeClass() == Atomic;
4342  }
4343  static bool classof(const AtomicType *) { return true; }
4344};
4345
4346/// A qualifier set is used to build a set of qualifiers.
4347class QualifierCollector : public Qualifiers {
4348public:
4349  QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4350
4351  /// Collect any qualifiers on the given type and return an
4352  /// unqualified type.  The qualifiers are assumed to be consistent
4353  /// with those already in the type.
4354  const Type *strip(QualType type) {
4355    addFastQualifiers(type.getLocalFastQualifiers());
4356    if (!type.hasLocalNonFastQualifiers())
4357      return type.getTypePtrUnsafe();
4358
4359    const ExtQuals *extQuals = type.getExtQualsUnsafe();
4360    addConsistentQualifiers(extQuals->getQualifiers());
4361    return extQuals->getBaseType();
4362  }
4363
4364  /// Apply the collected qualifiers to the given type.
4365  QualType apply(const ASTContext &Context, QualType QT) const;
4366
4367  /// Apply the collected qualifiers to the given type.
4368  QualType apply(const ASTContext &Context, const Type* T) const;
4369};
4370
4371
4372// Inline function definitions.
4373
4374inline const Type *QualType::getTypePtr() const {
4375  return getCommonPtr()->BaseType;
4376}
4377
4378inline const Type *QualType::getTypePtrOrNull() const {
4379  return (isNull() ? 0 : getCommonPtr()->BaseType);
4380}
4381
4382inline SplitQualType QualType::split() const {
4383  if (!hasLocalNonFastQualifiers())
4384    return SplitQualType(getTypePtrUnsafe(),
4385                         Qualifiers::fromFastMask(getLocalFastQualifiers()));
4386
4387  const ExtQuals *eq = getExtQualsUnsafe();
4388  Qualifiers qs = eq->getQualifiers();
4389  qs.addFastQualifiers(getLocalFastQualifiers());
4390  return SplitQualType(eq->getBaseType(), qs);
4391}
4392
4393inline Qualifiers QualType::getLocalQualifiers() const {
4394  Qualifiers Quals;
4395  if (hasLocalNonFastQualifiers())
4396    Quals = getExtQualsUnsafe()->getQualifiers();
4397  Quals.addFastQualifiers(getLocalFastQualifiers());
4398  return Quals;
4399}
4400
4401inline Qualifiers QualType::getQualifiers() const {
4402  Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4403  quals.addFastQualifiers(getLocalFastQualifiers());
4404  return quals;
4405}
4406
4407inline unsigned QualType::getCVRQualifiers() const {
4408  unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4409  cvr |= getLocalCVRQualifiers();
4410  return cvr;
4411}
4412
4413inline QualType QualType::getCanonicalType() const {
4414  QualType canon = getCommonPtr()->CanonicalType;
4415  return canon.withFastQualifiers(getLocalFastQualifiers());
4416}
4417
4418inline bool QualType::isCanonical() const {
4419  return getTypePtr()->isCanonicalUnqualified();
4420}
4421
4422inline bool QualType::isCanonicalAsParam() const {
4423  if (!isCanonical()) return false;
4424  if (hasLocalQualifiers()) return false;
4425
4426  const Type *T = getTypePtr();
4427  if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4428    return false;
4429
4430  return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4431}
4432
4433inline bool QualType::isConstQualified() const {
4434  return isLocalConstQualified() ||
4435         getCommonPtr()->CanonicalType.isLocalConstQualified();
4436}
4437
4438inline bool QualType::isRestrictQualified() const {
4439  return isLocalRestrictQualified() ||
4440         getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4441}
4442
4443
4444inline bool QualType::isVolatileQualified() const {
4445  return isLocalVolatileQualified() ||
4446         getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4447}
4448
4449inline bool QualType::hasQualifiers() const {
4450  return hasLocalQualifiers() ||
4451         getCommonPtr()->CanonicalType.hasLocalQualifiers();
4452}
4453
4454inline QualType QualType::getUnqualifiedType() const {
4455  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4456    return QualType(getTypePtr(), 0);
4457
4458  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4459}
4460
4461inline SplitQualType QualType::getSplitUnqualifiedType() const {
4462  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4463    return split();
4464
4465  return getSplitUnqualifiedTypeImpl(*this);
4466}
4467
4468inline void QualType::removeLocalConst() {
4469  removeLocalFastQualifiers(Qualifiers::Const);
4470}
4471
4472inline void QualType::removeLocalRestrict() {
4473  removeLocalFastQualifiers(Qualifiers::Restrict);
4474}
4475
4476inline void QualType::removeLocalVolatile() {
4477  removeLocalFastQualifiers(Qualifiers::Volatile);
4478}
4479
4480inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4481  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4482  assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4483
4484  // Fast path: we don't need to touch the slow qualifiers.
4485  removeLocalFastQualifiers(Mask);
4486}
4487
4488/// getAddressSpace - Return the address space of this type.
4489inline unsigned QualType::getAddressSpace() const {
4490  return getQualifiers().getAddressSpace();
4491}
4492
4493/// getObjCGCAttr - Return the gc attribute of this type.
4494inline Qualifiers::GC QualType::getObjCGCAttr() const {
4495  return getQualifiers().getObjCGCAttr();
4496}
4497
4498inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4499  if (const PointerType *PT = t.getAs<PointerType>()) {
4500    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4501      return FT->getExtInfo();
4502  } else if (const FunctionType *FT = t.getAs<FunctionType>())
4503    return FT->getExtInfo();
4504
4505  return FunctionType::ExtInfo();
4506}
4507
4508inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4509  return getFunctionExtInfo(*t);
4510}
4511
4512/// isMoreQualifiedThan - Determine whether this type is more
4513/// qualified than the Other type. For example, "const volatile int"
4514/// is more qualified than "const int", "volatile int", and
4515/// "int". However, it is not more qualified than "const volatile
4516/// int".
4517inline bool QualType::isMoreQualifiedThan(QualType other) const {
4518  Qualifiers myQuals = getQualifiers();
4519  Qualifiers otherQuals = other.getQualifiers();
4520  return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4521}
4522
4523/// isAtLeastAsQualifiedAs - Determine whether this type is at last
4524/// as qualified as the Other type. For example, "const volatile
4525/// int" is at least as qualified as "const int", "volatile int",
4526/// "int", and "const volatile int".
4527inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4528  return getQualifiers().compatiblyIncludes(other.getQualifiers());
4529}
4530
4531/// getNonReferenceType - If Type is a reference type (e.g., const
4532/// int&), returns the type that the reference refers to ("const
4533/// int"). Otherwise, returns the type itself. This routine is used
4534/// throughout Sema to implement C++ 5p6:
4535///
4536///   If an expression initially has the type "reference to T" (8.3.2,
4537///   8.5.3), the type is adjusted to "T" prior to any further
4538///   analysis, the expression designates the object or function
4539///   denoted by the reference, and the expression is an lvalue.
4540inline QualType QualType::getNonReferenceType() const {
4541  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4542    return RefType->getPointeeType();
4543  else
4544    return *this;
4545}
4546
4547inline bool QualType::isCForbiddenLValueType() const {
4548  return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4549          getTypePtr()->isFunctionType());
4550}
4551
4552/// \brief Tests whether the type is categorized as a fundamental type.
4553///
4554/// \returns True for types specified in C++0x [basic.fundamental].
4555inline bool Type::isFundamentalType() const {
4556  return isVoidType() ||
4557         // FIXME: It's really annoying that we don't have an
4558         // 'isArithmeticType()' which agrees with the standard definition.
4559         (isArithmeticType() && !isEnumeralType());
4560}
4561
4562/// \brief Tests whether the type is categorized as a compound type.
4563///
4564/// \returns True for types specified in C++0x [basic.compound].
4565inline bool Type::isCompoundType() const {
4566  // C++0x [basic.compound]p1:
4567  //   Compound types can be constructed in the following ways:
4568  //    -- arrays of objects of a given type [...];
4569  return isArrayType() ||
4570  //    -- functions, which have parameters of given types [...];
4571         isFunctionType() ||
4572  //    -- pointers to void or objects or functions [...];
4573         isPointerType() ||
4574  //    -- references to objects or functions of a given type. [...]
4575         isReferenceType() ||
4576  //    -- classes containing a sequence of objects of various types, [...];
4577         isRecordType() ||
4578  //    -- unions, which are classes capable of containing objects of different
4579  //               types at different times;
4580         isUnionType() ||
4581  //    -- enumerations, which comprise a set of named constant values. [...];
4582         isEnumeralType() ||
4583  //    -- pointers to non-static class members, [...].
4584         isMemberPointerType();
4585}
4586
4587inline bool Type::isFunctionType() const {
4588  return isa<FunctionType>(CanonicalType);
4589}
4590inline bool Type::isPointerType() const {
4591  return isa<PointerType>(CanonicalType);
4592}
4593inline bool Type::isAnyPointerType() const {
4594  return isPointerType() || isObjCObjectPointerType();
4595}
4596inline bool Type::isBlockPointerType() const {
4597  return isa<BlockPointerType>(CanonicalType);
4598}
4599inline bool Type::isReferenceType() const {
4600  return isa<ReferenceType>(CanonicalType);
4601}
4602inline bool Type::isLValueReferenceType() const {
4603  return isa<LValueReferenceType>(CanonicalType);
4604}
4605inline bool Type::isRValueReferenceType() const {
4606  return isa<RValueReferenceType>(CanonicalType);
4607}
4608inline bool Type::isFunctionPointerType() const {
4609  if (const PointerType *T = getAs<PointerType>())
4610    return T->getPointeeType()->isFunctionType();
4611  else
4612    return false;
4613}
4614inline bool Type::isMemberPointerType() const {
4615  return isa<MemberPointerType>(CanonicalType);
4616}
4617inline bool Type::isMemberFunctionPointerType() const {
4618  if (const MemberPointerType* T = getAs<MemberPointerType>())
4619    return T->isMemberFunctionPointer();
4620  else
4621    return false;
4622}
4623inline bool Type::isMemberDataPointerType() const {
4624  if (const MemberPointerType* T = getAs<MemberPointerType>())
4625    return T->isMemberDataPointer();
4626  else
4627    return false;
4628}
4629inline bool Type::isArrayType() const {
4630  return isa<ArrayType>(CanonicalType);
4631}
4632inline bool Type::isConstantArrayType() const {
4633  return isa<ConstantArrayType>(CanonicalType);
4634}
4635inline bool Type::isIncompleteArrayType() const {
4636  return isa<IncompleteArrayType>(CanonicalType);
4637}
4638inline bool Type::isVariableArrayType() const {
4639  return isa<VariableArrayType>(CanonicalType);
4640}
4641inline bool Type::isDependentSizedArrayType() const {
4642  return isa<DependentSizedArrayType>(CanonicalType);
4643}
4644inline bool Type::isBuiltinType() const {
4645  return isa<BuiltinType>(CanonicalType);
4646}
4647inline bool Type::isRecordType() const {
4648  return isa<RecordType>(CanonicalType);
4649}
4650inline bool Type::isEnumeralType() const {
4651  return isa<EnumType>(CanonicalType);
4652}
4653inline bool Type::isAnyComplexType() const {
4654  return isa<ComplexType>(CanonicalType);
4655}
4656inline bool Type::isVectorType() const {
4657  return isa<VectorType>(CanonicalType);
4658}
4659inline bool Type::isExtVectorType() const {
4660  return isa<ExtVectorType>(CanonicalType);
4661}
4662inline bool Type::isObjCObjectPointerType() const {
4663  return isa<ObjCObjectPointerType>(CanonicalType);
4664}
4665inline bool Type::isObjCObjectType() const {
4666  return isa<ObjCObjectType>(CanonicalType);
4667}
4668inline bool Type::isObjCObjectOrInterfaceType() const {
4669  return isa<ObjCInterfaceType>(CanonicalType) ||
4670    isa<ObjCObjectType>(CanonicalType);
4671}
4672inline bool Type::isAtomicType() const {
4673  return isa<AtomicType>(CanonicalType);
4674}
4675
4676inline bool Type::isObjCQualifiedIdType() const {
4677  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4678    return OPT->isObjCQualifiedIdType();
4679  return false;
4680}
4681inline bool Type::isObjCQualifiedClassType() const {
4682  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4683    return OPT->isObjCQualifiedClassType();
4684  return false;
4685}
4686inline bool Type::isObjCIdType() const {
4687  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4688    return OPT->isObjCIdType();
4689  return false;
4690}
4691inline bool Type::isObjCClassType() const {
4692  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4693    return OPT->isObjCClassType();
4694  return false;
4695}
4696inline bool Type::isObjCSelType() const {
4697  if (const PointerType *OPT = getAs<PointerType>())
4698    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4699  return false;
4700}
4701inline bool Type::isObjCBuiltinType() const {
4702  return isObjCIdType() || isObjCClassType() || isObjCSelType();
4703}
4704inline bool Type::isTemplateTypeParmType() const {
4705  return isa<TemplateTypeParmType>(CanonicalType);
4706}
4707
4708inline bool Type::isSpecificBuiltinType(unsigned K) const {
4709  if (const BuiltinType *BT = getAs<BuiltinType>())
4710    if (BT->getKind() == (BuiltinType::Kind) K)
4711      return true;
4712  return false;
4713}
4714
4715inline bool Type::isPlaceholderType() const {
4716  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4717    return BT->isPlaceholderType();
4718  return false;
4719}
4720
4721inline const BuiltinType *Type::getAsPlaceholderType() const {
4722  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4723    if (BT->isPlaceholderType())
4724      return BT;
4725  return 0;
4726}
4727
4728inline bool Type::isSpecificPlaceholderType(unsigned K) const {
4729  assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
4730  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4731    return (BT->getKind() == (BuiltinType::Kind) K);
4732  return false;
4733}
4734
4735inline bool Type::isNonOverloadPlaceholderType() const {
4736  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4737    return BT->isNonOverloadPlaceholderType();
4738  return false;
4739}
4740
4741/// \brief Determines whether this is a type for which one can define
4742/// an overloaded operator.
4743inline bool Type::isOverloadableType() const {
4744  return isDependentType() || isRecordType() || isEnumeralType();
4745}
4746
4747/// \brief Determines whether this type can decay to a pointer type.
4748inline bool Type::canDecayToPointerType() const {
4749  return isFunctionType() || isArrayType();
4750}
4751
4752inline bool Type::hasPointerRepresentation() const {
4753  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4754          isObjCObjectPointerType() || isNullPtrType());
4755}
4756
4757inline bool Type::hasObjCPointerRepresentation() const {
4758  return isObjCObjectPointerType();
4759}
4760
4761inline const Type *Type::getBaseElementTypeUnsafe() const {
4762  const Type *type = this;
4763  while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4764    type = arrayType->getElementType().getTypePtr();
4765  return type;
4766}
4767
4768/// Insertion operator for diagnostics.  This allows sending QualType's into a
4769/// diagnostic with <<.
4770inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4771                                           QualType T) {
4772  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4773                  DiagnosticsEngine::ak_qualtype);
4774  return DB;
4775}
4776
4777/// Insertion operator for partial diagnostics.  This allows sending QualType's
4778/// into a diagnostic with <<.
4779inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4780                                           QualType T) {
4781  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4782                  DiagnosticsEngine::ak_qualtype);
4783  return PD;
4784}
4785
4786// Helper class template that is used by Type::getAs to ensure that one does
4787// not try to look through a qualified type to get to an array type.
4788template<typename T,
4789         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4790                             llvm::is_base_of<ArrayType, T>::value)>
4791struct ArrayType_cannot_be_used_with_getAs { };
4792
4793template<typename T>
4794struct ArrayType_cannot_be_used_with_getAs<T, true>;
4795
4796/// Member-template getAs<specific type>'.
4797template <typename T> const T *Type::getAs() const {
4798  ArrayType_cannot_be_used_with_getAs<T> at;
4799  (void)at;
4800
4801  // If this is directly a T type, return it.
4802  if (const T *Ty = dyn_cast<T>(this))
4803    return Ty;
4804
4805  // If the canonical form of this type isn't the right kind, reject it.
4806  if (!isa<T>(CanonicalType))
4807    return 0;
4808
4809  // If this is a typedef for the type, strip the typedef off without
4810  // losing all typedef information.
4811  return cast<T>(getUnqualifiedDesugaredType());
4812}
4813
4814inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4815  // If this is directly an array type, return it.
4816  if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4817    return arr;
4818
4819  // If the canonical form of this type isn't the right kind, reject it.
4820  if (!isa<ArrayType>(CanonicalType))
4821    return 0;
4822
4823  // If this is a typedef for the type, strip the typedef off without
4824  // losing all typedef information.
4825  return cast<ArrayType>(getUnqualifiedDesugaredType());
4826}
4827
4828template <typename T> const T *Type::castAs() const {
4829  ArrayType_cannot_be_used_with_getAs<T> at;
4830  (void) at;
4831
4832  assert(isa<T>(CanonicalType));
4833  if (const T *ty = dyn_cast<T>(this)) return ty;
4834  return cast<T>(getUnqualifiedDesugaredType());
4835}
4836
4837inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4838  assert(isa<ArrayType>(CanonicalType));
4839  if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4840  return cast<ArrayType>(getUnqualifiedDesugaredType());
4841}
4842
4843}  // end namespace clang
4844
4845#endif
4846