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