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