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