Type.h revision caf383ae337966d67380b6b161fab17ec2b53d04
1//===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Type interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_TYPE_H
15#define LLVM_CLANG_AST_TYPE_H
16
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/AST/NestedNameSpecifier.h"
20#include "clang/AST/TemplateName.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/type_traits.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/PointerUnion.h"
27
28using llvm::isa;
29using llvm::cast;
30using llvm::cast_or_null;
31using llvm::dyn_cast;
32using llvm::dyn_cast_or_null;
33namespace clang {
34  enum {
35    TypeAlignmentInBits = 3,
36    TypeAlignment = 1 << TypeAlignmentInBits
37  };
38  class Type; class ExtQuals;
39}
40
41namespace llvm {
42  template <typename T>
43  class PointerLikeTypeTraits;
44  template<>
45  class PointerLikeTypeTraits< ::clang::Type*> {
46  public:
47    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
48    static inline ::clang::Type *getFromVoidPointer(void *P) {
49      return static_cast< ::clang::Type*>(P);
50    }
51    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
52  };
53  template<>
54  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
55  public:
56    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
57    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
58      return static_cast< ::clang::ExtQuals*>(P);
59    }
60    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
61  };
62}
63
64namespace clang {
65  class ASTContext;
66  class TypedefDecl;
67  class TemplateDecl;
68  class TemplateTypeParmDecl;
69  class NonTypeTemplateParmDecl;
70  class TemplateTemplateParmDecl;
71  class TagDecl;
72  class RecordDecl;
73  class CXXRecordDecl;
74  class EnumDecl;
75  class FieldDecl;
76  class ObjCInterfaceDecl;
77  class ObjCProtocolDecl;
78  class ObjCMethodDecl;
79  class UnresolvedUsingTypenameDecl;
80  class Expr;
81  class Stmt;
82  class SourceLocation;
83  class StmtIteratorBase;
84  class TemplateArgument;
85  class TemplateArgumentLoc;
86  class TemplateArgumentListInfo;
87  class QualifiedNameType;
88  struct PrintingPolicy;
89
90  // Provide forward declarations for all of the *Type classes
91#define TYPE(Class, Base) class Class##Type;
92#include "clang/AST/TypeNodes.def"
93
94/// Qualifiers - The collection of all-type qualifiers we support.
95/// Clang supports five independent qualifiers:
96/// * C99: const, volatile, and restrict
97/// * Embedded C (TR18037): address spaces
98/// * Objective C: the GC attributes (none, weak, or strong)
99class Qualifiers {
100public:
101  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
102    Const    = 0x1,
103    Restrict = 0x2,
104    Volatile = 0x4,
105    CVRMask = Const | Volatile | Restrict
106  };
107
108  enum GC {
109    GCNone = 0,
110    Weak,
111    Strong
112  };
113
114  enum {
115    /// The maximum supported address space number.
116    /// 24 bits should be enough for anyone.
117    MaxAddressSpace = 0xffffffu,
118
119    /// The width of the "fast" qualifier mask.
120    FastWidth = 2,
121
122    /// The fast qualifier mask.
123    FastMask = (1 << FastWidth) - 1
124  };
125
126  Qualifiers() : Mask(0) {}
127
128  static Qualifiers fromFastMask(unsigned Mask) {
129    Qualifiers Qs;
130    Qs.addFastQualifiers(Mask);
131    return Qs;
132  }
133
134  static Qualifiers fromCVRMask(unsigned CVR) {
135    Qualifiers Qs;
136    Qs.addCVRQualifiers(CVR);
137    return Qs;
138  }
139
140  // Deserialize qualifiers from an opaque representation.
141  static Qualifiers fromOpaqueValue(unsigned opaque) {
142    Qualifiers Qs;
143    Qs.Mask = opaque;
144    return Qs;
145  }
146
147  // Serialize these qualifiers into an opaque representation.
148  unsigned getAsOpaqueValue() const {
149    return Mask;
150  }
151
152  bool hasConst() const { return Mask & Const; }
153  void setConst(bool flag) {
154    Mask = (Mask & ~Const) | (flag ? Const : 0);
155  }
156  void removeConst() { Mask &= ~Const; }
157  void addConst() { Mask |= Const; }
158
159  bool hasVolatile() const { return Mask & Volatile; }
160  void setVolatile(bool flag) {
161    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
162  }
163  void removeVolatile() { Mask &= ~Volatile; }
164  void addVolatile() { Mask |= Volatile; }
165
166  bool hasRestrict() const { return Mask & Restrict; }
167  void setRestrict(bool flag) {
168    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
169  }
170  void removeRestrict() { Mask &= ~Restrict; }
171  void addRestrict() { Mask |= Restrict; }
172
173  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
174  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
175  void setCVRQualifiers(unsigned mask) {
176    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
177    Mask = (Mask & ~CVRMask) | mask;
178  }
179  void removeCVRQualifiers(unsigned mask) {
180    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
181    Mask &= ~mask;
182  }
183  void removeCVRQualifiers() {
184    removeCVRQualifiers(CVRMask);
185  }
186  void addCVRQualifiers(unsigned mask) {
187    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
188    Mask |= mask;
189  }
190
191  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
192  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
193  void setObjCGCAttr(GC type) {
194    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
195  }
196  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
197  void addObjCGCAttr(GC type) {
198    assert(type);
199    setObjCGCAttr(type);
200  }
201
202  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
203  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
204  void setAddressSpace(unsigned space) {
205    assert(space <= MaxAddressSpace);
206    Mask = (Mask & ~AddressSpaceMask)
207         | (((uint32_t) space) << AddressSpaceShift);
208  }
209  void removeAddressSpace() { setAddressSpace(0); }
210  void addAddressSpace(unsigned space) {
211    assert(space);
212    setAddressSpace(space);
213  }
214
215  // Fast qualifiers are those that can be allocated directly
216  // on a QualType object.
217  bool hasFastQualifiers() const { return getFastQualifiers(); }
218  unsigned getFastQualifiers() const { return Mask & FastMask; }
219  void setFastQualifiers(unsigned mask) {
220    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
221    Mask = (Mask & ~FastMask) | mask;
222  }
223  void removeFastQualifiers(unsigned mask) {
224    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
225    Mask &= ~mask;
226  }
227  void removeFastQualifiers() {
228    removeFastQualifiers(FastMask);
229  }
230  void addFastQualifiers(unsigned mask) {
231    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
232    Mask |= mask;
233  }
234
235  /// hasNonFastQualifiers - Return true if the set contains any
236  /// qualifiers which require an ExtQuals node to be allocated.
237  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
238  Qualifiers getNonFastQualifiers() const {
239    Qualifiers Quals = *this;
240    Quals.setFastQualifiers(0);
241    return Quals;
242  }
243
244  /// hasQualifiers - Return true if the set contains any qualifiers.
245  bool hasQualifiers() const { return Mask; }
246  bool empty() const { return !Mask; }
247
248  /// \brief Add the qualifiers from the given set to this set.
249  void addQualifiers(Qualifiers Q) {
250    // If the other set doesn't have any non-boolean qualifiers, just
251    // bit-or it in.
252    if (!(Q.Mask & ~CVRMask))
253      Mask |= Q.Mask;
254    else {
255      Mask |= (Q.Mask & CVRMask);
256      if (Q.hasAddressSpace())
257        addAddressSpace(Q.getAddressSpace());
258      if (Q.hasObjCGCAttr())
259        addObjCGCAttr(Q.getObjCGCAttr());
260    }
261  }
262
263  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
264  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
265
266  operator bool() const { return hasQualifiers(); }
267
268  Qualifiers &operator+=(Qualifiers R) {
269    addQualifiers(R);
270    return *this;
271  }
272
273  // Union two qualifier sets.  If an enumerated qualifier appears
274  // in both sets, use the one from the right.
275  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
276    L += R;
277    return L;
278  }
279
280  std::string getAsString() const;
281  std::string getAsString(const PrintingPolicy &Policy) const {
282    std::string Buffer;
283    getAsStringInternal(Buffer, Policy);
284    return Buffer;
285  }
286  void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
287
288  void Profile(llvm::FoldingSetNodeID &ID) const {
289    ID.AddInteger(Mask);
290  }
291
292private:
293
294  // bits:     |0 1 2|3 .. 4|5  ..  31|
295  //           |C R V|GCAttr|AddrSpace|
296  uint32_t Mask;
297
298  static const uint32_t GCAttrMask = 0x18;
299  static const uint32_t GCAttrShift = 3;
300  static const uint32_t AddressSpaceMask = ~(CVRMask | GCAttrMask);
301  static const uint32_t AddressSpaceShift = 5;
302};
303
304
305/// ExtQuals - We can encode up to three bits in the low bits of a
306/// type pointer, but there are many more type qualifiers that we want
307/// to be able to apply to an arbitrary type.  Therefore we have this
308/// struct, intended to be heap-allocated and used by QualType to
309/// store qualifiers.
310///
311/// The current design tags the 'const' and 'restrict' qualifiers in
312/// two low bits on the QualType pointer; a third bit records whether
313/// the pointer is an ExtQuals node.  'const' was chosen because it is
314/// orders of magnitude more common than the other two qualifiers, in
315/// both library and user code.  It's relatively rare to see
316/// 'restrict' in user code, but many standard C headers are saturated
317/// with 'restrict' declarations, so that representing them efficiently
318/// is a critical goal of this representation.
319class ExtQuals : public llvm::FoldingSetNode {
320  // NOTE: changing the fast qualifiers should be straightforward as
321  // long as you don't make 'const' non-fast.
322  // 1. Qualifiers:
323  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
324  //       Fast qualifiers must occupy the low-order bits.
325  //    b) Update Qualifiers::FastWidth and FastMask.
326  // 2. QualType:
327  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
328  //    b) Update remove{Volatile,Restrict}, defined near the end of
329  //       this header.
330  // 3. ASTContext:
331  //    a) Update get{Volatile,Restrict}Type.
332
333  /// Context - the context to which this set belongs.  We save this
334  /// here so that QualifierCollector can use it to reapply extended
335  /// qualifiers to an arbitrary type without requiring a context to
336  /// be pushed through every single API dealing with qualifiers.
337  ASTContext& Context;
338
339  /// BaseType - the underlying type that this qualifies
340  const Type *BaseType;
341
342  /// Quals - the immutable set of qualifiers applied by this
343  /// node;  always contains extended qualifiers.
344  Qualifiers Quals;
345
346public:
347  ExtQuals(ASTContext& Context, const Type *Base, Qualifiers Quals)
348    : Context(Context), BaseType(Base), Quals(Quals)
349  {
350    assert(Quals.hasNonFastQualifiers()
351           && "ExtQuals created with no fast qualifiers");
352    assert(!Quals.hasFastQualifiers()
353           && "ExtQuals created with fast qualifiers");
354  }
355
356  Qualifiers getQualifiers() const { return Quals; }
357
358  bool hasVolatile() const { return Quals.hasVolatile(); }
359
360  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
361  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
362
363  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
364  unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
365
366  const Type *getBaseType() const { return BaseType; }
367
368  ASTContext &getContext() const { return Context; }
369
370public:
371  void Profile(llvm::FoldingSetNodeID &ID) const {
372    Profile(ID, getBaseType(), Quals);
373  }
374  static void Profile(llvm::FoldingSetNodeID &ID,
375                      const Type *BaseType,
376                      Qualifiers Quals) {
377    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
378    ID.AddPointer(BaseType);
379    Quals.Profile(ID);
380  }
381};
382
383
384/// QualType - For efficiency, we don't store CV-qualified types as nodes on
385/// their own: instead each reference to a type stores the qualifiers.  This
386/// greatly reduces the number of nodes we need to allocate for types (for
387/// example we only need one for 'int', 'const int', 'volatile int',
388/// 'const volatile int', etc).
389///
390/// As an added efficiency bonus, instead of making this a pair, we
391/// just store the two bits we care about in the low bits of the
392/// pointer.  To handle the packing/unpacking, we make QualType be a
393/// simple wrapper class that acts like a smart pointer.  A third bit
394/// indicates whether there are extended qualifiers present, in which
395/// case the pointer points to a special structure.
396class QualType {
397  // Thankfully, these are efficiently composable.
398  llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
399                       Qualifiers::FastWidth> Value;
400
401  const ExtQuals *getExtQualsUnsafe() const {
402    return Value.getPointer().get<const ExtQuals*>();
403  }
404
405  const Type *getTypePtrUnsafe() const {
406    return Value.getPointer().get<const Type*>();
407  }
408
409  QualType getUnqualifiedTypeSlow() const;
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  Type *getTypePtr() const {
427    if (hasLocalNonFastQualifiers())
428      return const_cast<Type*>(getExtQualsUnsafe()->getBaseType());
429    return const_cast<Type*>(getTypePtrUnsafe());
430  }
431
432  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
433  static QualType getFromOpaquePtr(void *Ptr) {
434    QualType T;
435    T.Value.setFromOpaqueValue(Ptr);
436    return T;
437  }
438
439  Type &operator*() const {
440    return *getTypePtr();
441  }
442
443  Type *operator->() const {
444    return getTypePtr();
445  }
446
447  bool isCanonical() const;
448  bool isCanonicalAsParam() const;
449
450  /// isNull - Return true if this QualType doesn't point to a type yet.
451  bool isNull() const {
452    return Value.getPointer().isNull();
453  }
454
455  /// \brief Determine whether this particular QualType instance has the
456  /// "const" qualifier set, without looking through typedefs that may have
457  /// added "const" at a different level.
458  bool isLocalConstQualified() const {
459    return (getLocalFastQualifiers() & Qualifiers::Const);
460  }
461
462  /// \brief Determine whether this type is const-qualified.
463  bool isConstQualified() const;
464
465  /// \brief Determine whether this particular QualType instance has the
466  /// "restrict" qualifier set, without looking through typedefs that may have
467  /// added "restrict" at a different level.
468  bool isLocalRestrictQualified() const {
469    return (getLocalFastQualifiers() & Qualifiers::Restrict);
470  }
471
472  /// \brief Determine whether this type is restrict-qualified.
473  bool isRestrictQualified() const;
474
475  /// \brief Determine whether this particular QualType instance has the
476  /// "volatile" qualifier set, without looking through typedefs that may have
477  /// added "volatile" at a different level.
478  bool isLocalVolatileQualified() const {
479    return (hasLocalNonFastQualifiers() && getExtQualsUnsafe()->hasVolatile());
480  }
481
482  /// \brief Determine whether this type is volatile-qualified.
483  bool isVolatileQualified() const;
484
485  /// \brief Determine whether this particular QualType instance has any
486  /// qualifiers, without looking through any typedefs that might add
487  /// qualifiers at a different level.
488  bool hasLocalQualifiers() const {
489    return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
490  }
491
492  /// \brief Determine whether this type has any qualifiers.
493  bool hasQualifiers() const;
494
495  /// \brief Determine whether this particular QualType instance has any
496  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
497  /// instance.
498  bool hasLocalNonFastQualifiers() const {
499    return Value.getPointer().is<const ExtQuals*>();
500  }
501
502  /// \brief Retrieve the set of qualifiers local to this particular QualType
503  /// instance, not including any qualifiers acquired through typedefs or
504  /// other sugar.
505  Qualifiers getLocalQualifiers() const {
506    Qualifiers Quals;
507    if (hasLocalNonFastQualifiers())
508      Quals = getExtQualsUnsafe()->getQualifiers();
509    Quals.addFastQualifiers(getLocalFastQualifiers());
510    return Quals;
511  }
512
513  /// \brief Retrieve the set of qualifiers applied to this type.
514  Qualifiers getQualifiers() const;
515
516  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
517  /// local to this particular QualType instance, not including any qualifiers
518  /// acquired through typedefs or other sugar.
519  unsigned getLocalCVRQualifiers() const {
520    unsigned CVR = getLocalFastQualifiers();
521    if (isLocalVolatileQualified())
522      CVR |= Qualifiers::Volatile;
523    return CVR;
524  }
525
526  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
527  /// applied to this type.
528  unsigned getCVRQualifiers() const;
529
530  bool isConstant(ASTContext& Ctx) const {
531    return QualType::isConstant(*this, Ctx);
532  }
533
534  // Don't promise in the API that anything besides 'const' can be
535  // easily added.
536
537  /// addConst - add the specified type qualifier to this QualType.
538  void addConst() {
539    addFastQualifiers(Qualifiers::Const);
540  }
541  QualType withConst() const {
542    return withFastQualifiers(Qualifiers::Const);
543  }
544
545  void addFastQualifiers(unsigned TQs) {
546    assert(!(TQs & ~Qualifiers::FastMask)
547           && "non-fast qualifier bits set in mask!");
548    Value.setInt(Value.getInt() | TQs);
549  }
550
551  // FIXME: The remove* functions are semantically broken, because they might
552  // not remove a qualifier stored on a typedef. Most of the with* functions
553  // have the same problem.
554  void removeConst();
555  void removeVolatile();
556  void removeRestrict();
557  void removeCVRQualifiers(unsigned Mask);
558
559  void removeFastQualifiers() { Value.setInt(0); }
560  void removeFastQualifiers(unsigned Mask) {
561    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
562    Value.setInt(Value.getInt() & ~Mask);
563  }
564
565  // Creates a type with the given qualifiers in addition to any
566  // qualifiers already on this type.
567  QualType withFastQualifiers(unsigned TQs) const {
568    QualType T = *this;
569    T.addFastQualifiers(TQs);
570    return T;
571  }
572
573  // Creates a type with exactly the given fast qualifiers, removing
574  // any existing fast qualifiers.
575  QualType withExactFastQualifiers(unsigned TQs) const {
576    return withoutFastQualifiers().withFastQualifiers(TQs);
577  }
578
579  // Removes fast qualifiers, but leaves any extended qualifiers in place.
580  QualType withoutFastQualifiers() const {
581    QualType T = *this;
582    T.removeFastQualifiers();
583    return T;
584  }
585
586  /// \brief Return this type with all of the instance-specific qualifiers
587  /// removed, but without removing any qualifiers that may have been applied
588  /// through typedefs.
589  QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
590
591  /// \brief Return the unqualified form of the given type, which might be
592  /// desugared to eliminate qualifiers introduced via typedefs.
593  QualType getUnqualifiedType() const {
594    QualType T = getLocalUnqualifiedType();
595    if (!T.hasQualifiers())
596      return T;
597
598    return getUnqualifiedTypeSlow();
599  }
600
601  bool isMoreQualifiedThan(QualType Other) const;
602  bool isAtLeastAsQualifiedAs(QualType Other) const;
603  QualType getNonReferenceType() const;
604
605  /// getDesugaredType - Return the specified type with any "sugar" removed from
606  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
607  /// the type is already concrete, it returns it unmodified.  This is similar
608  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
609  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
610  /// concrete.
611  ///
612  /// Qualifiers are left in place.
613  QualType getDesugaredType() const {
614    return QualType::getDesugaredType(*this);
615  }
616
617  /// operator==/!= - Indicate whether the specified types and qualifiers are
618  /// identical.
619  friend bool operator==(const QualType &LHS, const QualType &RHS) {
620    return LHS.Value == RHS.Value;
621  }
622  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
623    return LHS.Value != RHS.Value;
624  }
625  std::string getAsString() const;
626
627  std::string getAsString(const PrintingPolicy &Policy) const {
628    std::string S;
629    getAsStringInternal(S, Policy);
630    return S;
631  }
632  void getAsStringInternal(std::string &Str,
633                           const PrintingPolicy &Policy) const;
634
635  void dump(const char *s) const;
636  void dump() const;
637
638  void Profile(llvm::FoldingSetNodeID &ID) const {
639    ID.AddPointer(getAsOpaquePtr());
640  }
641
642  /// getAddressSpace - Return the address space of this type.
643  inline unsigned getAddressSpace() const;
644
645  /// GCAttrTypesAttr - Returns gc attribute of this type.
646  inline Qualifiers::GC getObjCGCAttr() const;
647
648  /// isObjCGCWeak true when Type is objc's weak.
649  bool isObjCGCWeak() const {
650    return getObjCGCAttr() == Qualifiers::Weak;
651  }
652
653  /// isObjCGCStrong true when Type is objc's strong.
654  bool isObjCGCStrong() const {
655    return getObjCGCAttr() == Qualifiers::Strong;
656  }
657
658  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
659  /// false otherwise.
660  bool getNoReturnAttr() const;
661
662private:
663  // These methods are implemented in a separate translation unit;
664  // "static"-ize them to avoid creating temporary QualTypes in the
665  // caller.
666  static bool isConstant(QualType T, ASTContext& Ctx);
667  static QualType getDesugaredType(QualType T);
668};
669
670} // end clang.
671
672namespace llvm {
673/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
674/// to a specific Type class.
675template<> struct simplify_type<const ::clang::QualType> {
676  typedef ::clang::Type* SimpleType;
677  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
678    return Val.getTypePtr();
679  }
680};
681template<> struct simplify_type< ::clang::QualType>
682  : public simplify_type<const ::clang::QualType> {};
683
684// Teach SmallPtrSet that QualType is "basically a pointer".
685template<>
686class PointerLikeTypeTraits<clang::QualType> {
687public:
688  static inline void *getAsVoidPointer(clang::QualType P) {
689    return P.getAsOpaquePtr();
690  }
691  static inline clang::QualType getFromVoidPointer(void *P) {
692    return clang::QualType::getFromOpaquePtr(P);
693  }
694  // Various qualifiers go in low bits.
695  enum { NumLowBitsAvailable = 0 };
696};
697
698} // end namespace llvm
699
700namespace clang {
701
702/// Type - This is the base class of the type hierarchy.  A central concept
703/// with types is that each type always has a canonical type.  A canonical type
704/// is the type with any typedef names stripped out of it or the types it
705/// references.  For example, consider:
706///
707///  typedef int  foo;
708///  typedef foo* bar;
709///    'int *'    'foo *'    'bar'
710///
711/// There will be a Type object created for 'int'.  Since int is canonical, its
712/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
713/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
714/// there is a PointerType that represents 'int*', which, like 'int', is
715/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
716/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
717/// is also 'int*'.
718///
719/// Non-canonical types are useful for emitting diagnostics, without losing
720/// information about typedefs being used.  Canonical types are useful for type
721/// comparisons (they allow by-pointer equality tests) and useful for reasoning
722/// about whether something has a particular form (e.g. is a function type),
723/// because they implicitly, recursively, strip all typedefs out of a type.
724///
725/// Types, once created, are immutable.
726///
727class Type {
728public:
729  enum TypeClass {
730#define TYPE(Class, Base) Class,
731#define ABSTRACT_TYPE(Class, Base)
732#include "clang/AST/TypeNodes.def"
733    TagFirst = Record, TagLast = Enum
734  };
735
736protected:
737  enum { TypeClassBitSize = 6 };
738
739private:
740  QualType CanonicalType;
741
742  /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
743  bool Dependent : 1;
744
745  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
746  /// Note that this should stay at the end of the ivars for Type so that
747  /// subclasses can pack their bitfields into the same word.
748  unsigned TC : TypeClassBitSize;
749
750  Type(const Type&);           // DO NOT IMPLEMENT.
751  void operator=(const Type&); // DO NOT IMPLEMENT.
752protected:
753  // silence VC++ warning C4355: 'this' : used in base member initializer list
754  Type *this_() { return this; }
755  Type(TypeClass tc, QualType Canonical, bool dependent)
756    : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical),
757      Dependent(dependent), TC(tc) {}
758  virtual ~Type() {}
759  virtual void Destroy(ASTContext& C);
760  friend class ASTContext;
761
762public:
763  TypeClass getTypeClass() const { return static_cast<TypeClass>(TC); }
764
765  bool isCanonicalUnqualified() const {
766    return CanonicalType.getTypePtr() == this;
767  }
768
769  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
770  /// object types, function types, and incomplete types.
771
772  /// \brief Determines whether the type describes an object in memory.
773  ///
774  /// Note that this definition of object type corresponds to the C++
775  /// definition of object type, which includes incomplete types, as
776  /// opposed to the C definition (which does not include incomplete
777  /// types).
778  bool isObjectType() const;
779
780  /// isIncompleteType - Return true if this is an incomplete type.
781  /// A type that can describe objects, but which lacks information needed to
782  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
783  /// routine will need to determine if the size is actually required.
784  bool isIncompleteType() const;
785
786  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
787  /// type, in other words, not a function type.
788  bool isIncompleteOrObjectType() const {
789    return !isFunctionType();
790  }
791
792  /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10).
793  bool isPODType() const;
794
795  /// isLiteralType - Return true if this is a literal type
796  /// (C++0x [basic.types]p10)
797  bool isLiteralType() const;
798
799  /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array
800  /// types that have a non-constant expression. This does not include "[]".
801  bool isVariablyModifiedType() const;
802
803  /// Helper methods to distinguish type categories. All type predicates
804  /// operate on the canonical type, ignoring typedefs and qualifiers.
805
806  /// isSpecificBuiltinType - Test for a particular builtin type.
807  bool isSpecificBuiltinType(unsigned K) const;
808
809  /// isIntegerType() does *not* include complex integers (a GCC extension).
810  /// isComplexIntegerType() can be used to test for complex integers.
811  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
812  bool isEnumeralType() const;
813  bool isBooleanType() const;
814  bool isCharType() const;
815  bool isWideCharType() const;
816  bool isIntegralType() const;
817
818  /// Floating point categories.
819  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
820  /// isComplexType() does *not* include complex integers (a GCC extension).
821  /// isComplexIntegerType() can be used to test for complex integers.
822  bool isComplexType() const;      // C99 6.2.5p11 (complex)
823  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
824  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
825  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
826  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
827  bool isVoidType() const;         // C99 6.2.5p19
828  bool isDerivedType() const;      // C99 6.2.5p20
829  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
830  bool isAggregateType() const;
831
832  // Type Predicates: Check to see if this type is structurally the specified
833  // type, ignoring typedefs and qualifiers.
834  bool isFunctionType() const;
835  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
836  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
837  bool isPointerType() const;
838  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
839  bool isBlockPointerType() const;
840  bool isVoidPointerType() const;
841  bool isReferenceType() const;
842  bool isLValueReferenceType() const;
843  bool isRValueReferenceType() const;
844  bool isFunctionPointerType() const;
845  bool isMemberPointerType() const;
846  bool isMemberFunctionPointerType() const;
847  bool isArrayType() const;
848  bool isConstantArrayType() const;
849  bool isIncompleteArrayType() const;
850  bool isVariableArrayType() const;
851  bool isDependentSizedArrayType() const;
852  bool isRecordType() const;
853  bool isClassType() const;
854  bool isStructureType() const;
855  bool isUnionType() const;
856  bool isComplexIntegerType() const;            // GCC _Complex integer type.
857  bool isVectorType() const;                    // GCC vector type.
858  bool isExtVectorType() const;                 // Extended vector type.
859  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
860  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
861  // for the common case.
862  bool isObjCInterfaceType() const;             // NSString or NSString<foo>
863  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
864  bool isObjCQualifiedIdType() const;           // id<foo>
865  bool isObjCQualifiedClassType() const;        // Class<foo>
866  bool isObjCIdType() const;                    // id
867  bool isObjCClassType() const;                 // Class
868  bool isObjCSelType() const;                 // Class
869  bool isObjCBuiltinType() const;               // 'id' or 'Class'
870  bool isTemplateTypeParmType() const;          // C++ template type parameter
871  bool isNullPtrType() const;                   // C++0x nullptr_t
872
873  /// isDependentType - Whether this type is a dependent type, meaning
874  /// that its definition somehow depends on a template parameter
875  /// (C++ [temp.dep.type]).
876  bool isDependentType() const { return Dependent; }
877  bool isOverloadableType() const;
878
879  /// hasPointerRepresentation - Whether this type is represented
880  /// natively as a pointer; this includes pointers, references, block
881  /// pointers, and Objective-C interface, qualified id, and qualified
882  /// interface types, as well as nullptr_t.
883  bool hasPointerRepresentation() const;
884
885  /// hasObjCPointerRepresentation - Whether this type can represent
886  /// an objective pointer type for the purpose of GC'ability
887  bool hasObjCPointerRepresentation() const;
888
889  // Type Checking Functions: Check to see if this type is structurally the
890  // specified type, ignoring typedefs and qualifiers, and return a pointer to
891  // the best type we can.
892  const RecordType *getAsStructureType() const;
893  /// NOTE: getAs*ArrayType are methods on ASTContext.
894  const RecordType *getAsUnionType() const;
895  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
896  // The following is a convenience method that returns an ObjCObjectPointerType
897  // for object declared using an interface.
898  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
899  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
900  const ObjCInterfaceType *getAsObjCQualifiedInterfaceType() const;
901  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
902
903  // Member-template getAs<specific type>'.  This scheme will eventually
904  // replace the specific getAsXXXX methods above.
905  //
906  // There are some specializations of this member template listed
907  // immediately following this class.
908  template <typename T> const T *getAs() const;
909
910  /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC
911  /// interface, return the interface type, otherwise return null.
912  const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const;
913
914  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
915  /// element type of the array, potentially with type qualifiers missing.
916  /// This method should never be used when type qualifiers are meaningful.
917  const Type *getArrayElementTypeNoTypeQual() const;
918
919  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
920  /// pointer, this returns the respective pointee.
921  QualType getPointeeType() const;
922
923  /// getUnqualifiedDesugaredType() - Return the specified type with
924  /// any "sugar" removed from the type, removing any typedefs,
925  /// typeofs, etc., as well as any qualifiers.
926  const Type *getUnqualifiedDesugaredType() const;
927
928  /// More type predicates useful for type checking/promotion
929  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
930
931  /// isSignedIntegerType - Return true if this is an integer type that is
932  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
933  /// an enum decl which has a signed representation, or a vector of signed
934  /// integer element type.
935  bool isSignedIntegerType() const;
936
937  /// isUnsignedIntegerType - Return true if this is an integer type that is
938  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
939  /// decl which has an unsigned representation, or a vector of unsigned integer
940  /// element type.
941  bool isUnsignedIntegerType() const;
942
943  /// isConstantSizeType - Return true if this is not a variable sized type,
944  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
945  /// incomplete types.
946  bool isConstantSizeType() const;
947
948  /// isSpecifierType - Returns true if this type can be represented by some
949  /// set of type specifiers.
950  bool isSpecifierType() const;
951
952  const char *getTypeClassName() const;
953
954  QualType getCanonicalTypeInternal() const { return CanonicalType; }
955  void dump() const;
956  static bool classof(const Type *) { return true; }
957};
958
959template <> inline const TypedefType *Type::getAs() const {
960  return dyn_cast<TypedefType>(this);
961}
962
963// We can do canonical leaf types faster, because we don't have to
964// worry about preserving child type decoration.
965#define TYPE(Class, Base)
966#define LEAF_TYPE(Class) \
967template <> inline const Class##Type *Type::getAs() const { \
968  return dyn_cast<Class##Type>(CanonicalType); \
969}
970#include "clang/AST/TypeNodes.def"
971
972
973/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
974/// types are always canonical and have a literal name field.
975class BuiltinType : public Type {
976public:
977  enum Kind {
978    Void,
979
980    Bool,     // This is bool and/or _Bool.
981    Char_U,   // This is 'char' for targets where char is unsigned.
982    UChar,    // This is explicitly qualified unsigned char.
983    Char16,   // This is 'char16_t' for C++.
984    Char32,   // This is 'char32_t' for C++.
985    UShort,
986    UInt,
987    ULong,
988    ULongLong,
989    UInt128,  // __uint128_t
990
991    Char_S,   // This is 'char' for targets where char is signed.
992    SChar,    // This is explicitly qualified signed char.
993    WChar,    // This is 'wchar_t' for C++.
994    Short,
995    Int,
996    Long,
997    LongLong,
998    Int128,   // __int128_t
999
1000    Float, Double, LongDouble,
1001
1002    NullPtr,  // This is the type of C++0x 'nullptr'.
1003
1004    Overload,  // This represents the type of an overloaded function declaration.
1005    Dependent, // This represents the type of a type-dependent expression.
1006
1007    UndeducedAuto, // In C++0x, this represents the type of an auto variable
1008                   // that has not been deduced yet.
1009    ObjCId,    // This represents the ObjC 'id' type.
1010    ObjCClass, // This represents the ObjC 'Class' type.
1011    ObjCSel    // This represents the ObjC 'SEL' type.
1012  };
1013private:
1014  Kind TypeKind;
1015public:
1016  BuiltinType(Kind K)
1017    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
1018      TypeKind(K) {}
1019
1020  Kind getKind() const { return TypeKind; }
1021  const char *getName(const LangOptions &LO) const;
1022
1023  bool isSugared() const { return false; }
1024  QualType desugar() const { return QualType(this, 0); }
1025
1026  bool isInteger() const {
1027    return TypeKind >= Bool && TypeKind <= Int128;
1028  }
1029
1030  bool isSignedInteger() const {
1031    return TypeKind >= Char_S && TypeKind <= Int128;
1032  }
1033
1034  bool isUnsignedInteger() const {
1035    return TypeKind >= Bool && TypeKind <= UInt128;
1036  }
1037
1038  bool isFloatingPoint() const {
1039    return TypeKind >= Float && TypeKind <= LongDouble;
1040  }
1041
1042  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1043  static bool classof(const BuiltinType *) { return true; }
1044};
1045
1046/// FixedWidthIntType - Used for arbitrary width types that we either don't
1047/// want to or can't map to named integer types.  These always have a lower
1048/// integer rank than builtin types of the same width.
1049class FixedWidthIntType : public Type {
1050private:
1051  unsigned Width;
1052  bool Signed;
1053public:
1054  FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false),
1055                                          Width(W), Signed(S) {}
1056
1057  unsigned getWidth() const { return Width; }
1058  bool isSigned() const { return Signed; }
1059  const char *getName() const;
1060
1061  bool isSugared() const { return false; }
1062  QualType desugar() const { return QualType(this, 0); }
1063
1064  static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; }
1065  static bool classof(const FixedWidthIntType *) { return true; }
1066};
1067
1068/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1069/// types (_Complex float etc) as well as the GCC integer complex extensions.
1070///
1071class ComplexType : public Type, public llvm::FoldingSetNode {
1072  QualType ElementType;
1073  ComplexType(QualType Element, QualType CanonicalPtr) :
1074    Type(Complex, CanonicalPtr, Element->isDependentType()),
1075    ElementType(Element) {
1076  }
1077  friend class ASTContext;  // ASTContext creates these.
1078public:
1079  QualType getElementType() const { return ElementType; }
1080
1081  bool isSugared() const { return false; }
1082  QualType desugar() const { return QualType(this, 0); }
1083
1084  void Profile(llvm::FoldingSetNodeID &ID) {
1085    Profile(ID, getElementType());
1086  }
1087  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1088    ID.AddPointer(Element.getAsOpaquePtr());
1089  }
1090
1091  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1092  static bool classof(const ComplexType *) { return true; }
1093};
1094
1095/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1096///
1097class PointerType : public Type, public llvm::FoldingSetNode {
1098  QualType PointeeType;
1099
1100  PointerType(QualType Pointee, QualType CanonicalPtr) :
1101    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1102  }
1103  friend class ASTContext;  // ASTContext creates these.
1104public:
1105
1106  QualType getPointeeType() const { return PointeeType; }
1107
1108  bool isSugared() const { return false; }
1109  QualType desugar() const { return QualType(this, 0); }
1110
1111  void Profile(llvm::FoldingSetNodeID &ID) {
1112    Profile(ID, getPointeeType());
1113  }
1114  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1115    ID.AddPointer(Pointee.getAsOpaquePtr());
1116  }
1117
1118  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1119  static bool classof(const PointerType *) { return true; }
1120};
1121
1122/// BlockPointerType - pointer to a block type.
1123/// This type is to represent types syntactically represented as
1124/// "void (^)(int)", etc. Pointee is required to always be a function type.
1125///
1126class BlockPointerType : public Type, public llvm::FoldingSetNode {
1127  QualType PointeeType;  // Block is some kind of pointer type
1128  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1129    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1130    PointeeType(Pointee) {
1131  }
1132  friend class ASTContext;  // ASTContext creates these.
1133public:
1134
1135  // Get the pointee type. Pointee is required to always be a function type.
1136  QualType getPointeeType() const { return PointeeType; }
1137
1138  bool isSugared() const { return false; }
1139  QualType desugar() const { return QualType(this, 0); }
1140
1141  void Profile(llvm::FoldingSetNodeID &ID) {
1142      Profile(ID, getPointeeType());
1143  }
1144  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1145      ID.AddPointer(Pointee.getAsOpaquePtr());
1146  }
1147
1148  static bool classof(const Type *T) {
1149    return T->getTypeClass() == BlockPointer;
1150  }
1151  static bool classof(const BlockPointerType *) { return true; }
1152};
1153
1154/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1155///
1156class ReferenceType : public Type, public llvm::FoldingSetNode {
1157  QualType PointeeType;
1158
1159  /// True if the type was originally spelled with an lvalue sigil.
1160  /// This is never true of rvalue references but can also be false
1161  /// on lvalue references because of C++0x [dcl.typedef]p9,
1162  /// as follows:
1163  ///
1164  ///   typedef int &ref;    // lvalue, spelled lvalue
1165  ///   typedef int &&rvref; // rvalue
1166  ///   ref &a;              // lvalue, inner ref, spelled lvalue
1167  ///   ref &&a;             // lvalue, inner ref
1168  ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1169  ///   rvref &&a;           // rvalue, inner ref
1170  bool SpelledAsLValue;
1171
1172  /// True if the inner type is a reference type.  This only happens
1173  /// in non-canonical forms.
1174  bool InnerRef;
1175
1176protected:
1177  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1178                bool SpelledAsLValue) :
1179    Type(tc, CanonicalRef, Referencee->isDependentType()),
1180    PointeeType(Referencee), SpelledAsLValue(SpelledAsLValue),
1181    InnerRef(Referencee->isReferenceType()) {
1182  }
1183public:
1184  bool isSpelledAsLValue() const { return SpelledAsLValue; }
1185
1186  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1187  QualType getPointeeType() const {
1188    // FIXME: this might strip inner qualifiers; okay?
1189    const ReferenceType *T = this;
1190    while (T->InnerRef)
1191      T = T->PointeeType->getAs<ReferenceType>();
1192    return T->PointeeType;
1193  }
1194
1195  void Profile(llvm::FoldingSetNodeID &ID) {
1196    Profile(ID, PointeeType, SpelledAsLValue);
1197  }
1198  static void Profile(llvm::FoldingSetNodeID &ID,
1199                      QualType Referencee,
1200                      bool SpelledAsLValue) {
1201    ID.AddPointer(Referencee.getAsOpaquePtr());
1202    ID.AddBoolean(SpelledAsLValue);
1203  }
1204
1205  static bool classof(const Type *T) {
1206    return T->getTypeClass() == LValueReference ||
1207           T->getTypeClass() == RValueReference;
1208  }
1209  static bool classof(const ReferenceType *) { return true; }
1210};
1211
1212/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1213///
1214class LValueReferenceType : public ReferenceType {
1215  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1216                      bool SpelledAsLValue) :
1217    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1218  {}
1219  friend class ASTContext; // ASTContext creates these
1220public:
1221  bool isSugared() const { return false; }
1222  QualType desugar() const { return QualType(this, 0); }
1223
1224  static bool classof(const Type *T) {
1225    return T->getTypeClass() == LValueReference;
1226  }
1227  static bool classof(const LValueReferenceType *) { return true; }
1228};
1229
1230/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1231///
1232class RValueReferenceType : public ReferenceType {
1233  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1234    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1235  }
1236  friend class ASTContext; // ASTContext creates these
1237public:
1238  bool isSugared() const { return false; }
1239  QualType desugar() const { return QualType(this, 0); }
1240
1241  static bool classof(const Type *T) {
1242    return T->getTypeClass() == RValueReference;
1243  }
1244  static bool classof(const RValueReferenceType *) { return true; }
1245};
1246
1247/// MemberPointerType - C++ 8.3.3 - Pointers to members
1248///
1249class MemberPointerType : public Type, public llvm::FoldingSetNode {
1250  QualType PointeeType;
1251  /// The class of which the pointee is a member. Must ultimately be a
1252  /// RecordType, but could be a typedef or a template parameter too.
1253  const Type *Class;
1254
1255  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1256    Type(MemberPointer, CanonicalPtr,
1257         Cls->isDependentType() || Pointee->isDependentType()),
1258    PointeeType(Pointee), Class(Cls) {
1259  }
1260  friend class ASTContext; // ASTContext creates these.
1261public:
1262
1263  QualType getPointeeType() const { return PointeeType; }
1264
1265  const Type *getClass() const { return Class; }
1266
1267  bool isSugared() const { return false; }
1268  QualType desugar() const { return QualType(this, 0); }
1269
1270  void Profile(llvm::FoldingSetNodeID &ID) {
1271    Profile(ID, getPointeeType(), getClass());
1272  }
1273  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1274                      const Type *Class) {
1275    ID.AddPointer(Pointee.getAsOpaquePtr());
1276    ID.AddPointer(Class);
1277  }
1278
1279  static bool classof(const Type *T) {
1280    return T->getTypeClass() == MemberPointer;
1281  }
1282  static bool classof(const MemberPointerType *) { return true; }
1283};
1284
1285/// ArrayType - C99 6.7.5.2 - Array Declarators.
1286///
1287class ArrayType : public Type, public llvm::FoldingSetNode {
1288public:
1289  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1290  /// an array with a static size (e.g. int X[static 4]), or an array
1291  /// with a star size (e.g. int X[*]).
1292  /// 'static' is only allowed on function parameters.
1293  enum ArraySizeModifier {
1294    Normal, Static, Star
1295  };
1296private:
1297  /// ElementType - The element type of the array.
1298  QualType ElementType;
1299
1300  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1301  /// NOTE: These fields are packed into the bitfields space in the Type class.
1302  unsigned SizeModifier : 2;
1303
1304  /// IndexTypeQuals - Capture qualifiers in declarations like:
1305  /// 'int X[static restrict 4]'. For function parameters only.
1306  unsigned IndexTypeQuals : 3;
1307
1308protected:
1309  // C++ [temp.dep.type]p1:
1310  //   A type is dependent if it is...
1311  //     - an array type constructed from any dependent type or whose
1312  //       size is specified by a constant expression that is
1313  //       value-dependent,
1314  ArrayType(TypeClass tc, QualType et, QualType can,
1315            ArraySizeModifier sm, unsigned tq)
1316    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1317      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1318
1319  friend class ASTContext;  // ASTContext creates these.
1320public:
1321  QualType getElementType() const { return ElementType; }
1322  ArraySizeModifier getSizeModifier() const {
1323    return ArraySizeModifier(SizeModifier);
1324  }
1325  Qualifiers getIndexTypeQualifiers() const {
1326    return Qualifiers::fromCVRMask(IndexTypeQuals);
1327  }
1328  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1329
1330  static bool classof(const Type *T) {
1331    return T->getTypeClass() == ConstantArray ||
1332           T->getTypeClass() == VariableArray ||
1333           T->getTypeClass() == IncompleteArray ||
1334           T->getTypeClass() == DependentSizedArray;
1335  }
1336  static bool classof(const ArrayType *) { return true; }
1337};
1338
1339/// ConstantArrayType - This class represents the canonical version of
1340/// C arrays with a specified constant size.  For example, the canonical
1341/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1342/// type is 'int' and the size is 404.
1343class ConstantArrayType : public ArrayType {
1344  llvm::APInt Size; // Allows us to unique the type.
1345
1346  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1347                    ArraySizeModifier sm, unsigned tq)
1348    : ArrayType(ConstantArray, et, can, sm, tq),
1349      Size(size) {}
1350protected:
1351  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1352                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1353    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1354  friend class ASTContext;  // ASTContext creates these.
1355public:
1356  const llvm::APInt &getSize() const { return Size; }
1357  bool isSugared() const { return false; }
1358  QualType desugar() const { return QualType(this, 0); }
1359
1360  void Profile(llvm::FoldingSetNodeID &ID) {
1361    Profile(ID, getElementType(), getSize(),
1362            getSizeModifier(), getIndexTypeCVRQualifiers());
1363  }
1364  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1365                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1366                      unsigned TypeQuals) {
1367    ID.AddPointer(ET.getAsOpaquePtr());
1368    ID.AddInteger(ArraySize.getZExtValue());
1369    ID.AddInteger(SizeMod);
1370    ID.AddInteger(TypeQuals);
1371  }
1372  static bool classof(const Type *T) {
1373    return T->getTypeClass() == ConstantArray;
1374  }
1375  static bool classof(const ConstantArrayType *) { return true; }
1376};
1377
1378/// IncompleteArrayType - This class represents C arrays with an unspecified
1379/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1380/// type is 'int' and the size is unspecified.
1381class IncompleteArrayType : public ArrayType {
1382
1383  IncompleteArrayType(QualType et, QualType can,
1384                      ArraySizeModifier sm, unsigned tq)
1385    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1386  friend class ASTContext;  // ASTContext creates these.
1387public:
1388  bool isSugared() const { return false; }
1389  QualType desugar() const { return QualType(this, 0); }
1390
1391  static bool classof(const Type *T) {
1392    return T->getTypeClass() == IncompleteArray;
1393  }
1394  static bool classof(const IncompleteArrayType *) { return true; }
1395
1396  friend class StmtIteratorBase;
1397
1398  void Profile(llvm::FoldingSetNodeID &ID) {
1399    Profile(ID, getElementType(), getSizeModifier(),
1400            getIndexTypeCVRQualifiers());
1401  }
1402
1403  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1404                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1405    ID.AddPointer(ET.getAsOpaquePtr());
1406    ID.AddInteger(SizeMod);
1407    ID.AddInteger(TypeQuals);
1408  }
1409};
1410
1411/// VariableArrayType - This class represents C arrays with a specified size
1412/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1413/// Since the size expression is an arbitrary expression, we store it as such.
1414///
1415/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1416/// should not be: two lexically equivalent variable array types could mean
1417/// different things, for example, these variables do not have the same type
1418/// dynamically:
1419///
1420/// void foo(int x) {
1421///   int Y[x];
1422///   ++x;
1423///   int Z[x];
1424/// }
1425///
1426class VariableArrayType : public ArrayType {
1427  /// SizeExpr - An assignment expression. VLA's are only permitted within
1428  /// a function block.
1429  Stmt *SizeExpr;
1430  /// Brackets - The left and right array brackets.
1431  SourceRange Brackets;
1432
1433  VariableArrayType(QualType et, QualType can, Expr *e,
1434                    ArraySizeModifier sm, unsigned tq,
1435                    SourceRange brackets)
1436    : ArrayType(VariableArray, et, can, sm, tq),
1437      SizeExpr((Stmt*) e), Brackets(brackets) {}
1438  friend class ASTContext;  // ASTContext creates these.
1439  virtual void Destroy(ASTContext& C);
1440
1441public:
1442  Expr *getSizeExpr() const {
1443    // We use C-style casts instead of cast<> here because we do not wish
1444    // to have a dependency of Type.h on Stmt.h/Expr.h.
1445    return (Expr*) SizeExpr;
1446  }
1447  SourceRange getBracketsRange() const { return Brackets; }
1448  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1449  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1450
1451  bool isSugared() const { return false; }
1452  QualType desugar() const { return QualType(this, 0); }
1453
1454  static bool classof(const Type *T) {
1455    return T->getTypeClass() == VariableArray;
1456  }
1457  static bool classof(const VariableArrayType *) { return true; }
1458
1459  friend class StmtIteratorBase;
1460
1461  void Profile(llvm::FoldingSetNodeID &ID) {
1462    assert(0 && "Cannnot unique VariableArrayTypes.");
1463  }
1464};
1465
1466/// DependentSizedArrayType - This type represents an array type in
1467/// C++ whose size is a value-dependent expression. For example:
1468///
1469/// \code
1470/// template<typename T, int Size>
1471/// class array {
1472///   T data[Size];
1473/// };
1474/// \endcode
1475///
1476/// For these types, we won't actually know what the array bound is
1477/// until template instantiation occurs, at which point this will
1478/// become either a ConstantArrayType or a VariableArrayType.
1479class DependentSizedArrayType : public ArrayType {
1480  ASTContext &Context;
1481
1482  /// \brief An assignment expression that will instantiate to the
1483  /// size of the array.
1484  ///
1485  /// The expression itself might be NULL, in which case the array
1486  /// type will have its size deduced from an initializer.
1487  Stmt *SizeExpr;
1488
1489  /// Brackets - The left and right array brackets.
1490  SourceRange Brackets;
1491
1492  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1493                          Expr *e, ArraySizeModifier sm, unsigned tq,
1494                          SourceRange brackets)
1495    : ArrayType(DependentSizedArray, et, can, sm, tq),
1496      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1497  friend class ASTContext;  // ASTContext creates these.
1498  virtual void Destroy(ASTContext& C);
1499
1500public:
1501  Expr *getSizeExpr() const {
1502    // We use C-style casts instead of cast<> here because we do not wish
1503    // to have a dependency of Type.h on Stmt.h/Expr.h.
1504    return (Expr*) SizeExpr;
1505  }
1506  SourceRange getBracketsRange() const { return Brackets; }
1507  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1508  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1509
1510  bool isSugared() const { return false; }
1511  QualType desugar() const { return QualType(this, 0); }
1512
1513  static bool classof(const Type *T) {
1514    return T->getTypeClass() == DependentSizedArray;
1515  }
1516  static bool classof(const DependentSizedArrayType *) { return true; }
1517
1518  friend class StmtIteratorBase;
1519
1520
1521  void Profile(llvm::FoldingSetNodeID &ID) {
1522    Profile(ID, Context, getElementType(),
1523            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1524  }
1525
1526  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1527                      QualType ET, ArraySizeModifier SizeMod,
1528                      unsigned TypeQuals, Expr *E);
1529};
1530
1531/// DependentSizedExtVectorType - This type represent an extended vector type
1532/// where either the type or size is dependent. For example:
1533/// @code
1534/// template<typename T, int Size>
1535/// class vector {
1536///   typedef T __attribute__((ext_vector_type(Size))) type;
1537/// }
1538/// @endcode
1539class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1540  ASTContext &Context;
1541  Expr *SizeExpr;
1542  /// ElementType - The element type of the array.
1543  QualType ElementType;
1544  SourceLocation loc;
1545
1546  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1547                              QualType can, Expr *SizeExpr, SourceLocation loc)
1548    : Type (DependentSizedExtVector, can, true),
1549      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1550      loc(loc) {}
1551  friend class ASTContext;
1552  virtual void Destroy(ASTContext& C);
1553
1554public:
1555  Expr *getSizeExpr() const { return SizeExpr; }
1556  QualType getElementType() const { return ElementType; }
1557  SourceLocation getAttributeLoc() const { return loc; }
1558
1559  bool isSugared() const { return false; }
1560  QualType desugar() const { return QualType(this, 0); }
1561
1562  static bool classof(const Type *T) {
1563    return T->getTypeClass() == DependentSizedExtVector;
1564  }
1565  static bool classof(const DependentSizedExtVectorType *) { return true; }
1566
1567  void Profile(llvm::FoldingSetNodeID &ID) {
1568    Profile(ID, Context, getElementType(), getSizeExpr());
1569  }
1570
1571  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1572                      QualType ElementType, Expr *SizeExpr);
1573};
1574
1575
1576/// VectorType - GCC generic vector type. This type is created using
1577/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1578/// bytes. Since the constructor takes the number of vector elements, the
1579/// client is responsible for converting the size into the number of elements.
1580class VectorType : public Type, public llvm::FoldingSetNode {
1581protected:
1582  /// ElementType - The element type of the vector.
1583  QualType ElementType;
1584
1585  /// NumElements - The number of elements in the vector.
1586  unsigned NumElements;
1587
1588  VectorType(QualType vecType, unsigned nElements, QualType canonType) :
1589    Type(Vector, canonType, vecType->isDependentType()),
1590    ElementType(vecType), NumElements(nElements) {}
1591  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1592             QualType canonType)
1593    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1594      NumElements(nElements) {}
1595  friend class ASTContext;  // ASTContext creates these.
1596public:
1597
1598  QualType getElementType() const { return ElementType; }
1599  unsigned getNumElements() const { return NumElements; }
1600
1601  bool isSugared() const { return false; }
1602  QualType desugar() const { return QualType(this, 0); }
1603
1604  void Profile(llvm::FoldingSetNodeID &ID) {
1605    Profile(ID, getElementType(), getNumElements(), getTypeClass());
1606  }
1607  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1608                      unsigned NumElements, TypeClass TypeClass) {
1609    ID.AddPointer(ElementType.getAsOpaquePtr());
1610    ID.AddInteger(NumElements);
1611    ID.AddInteger(TypeClass);
1612  }
1613  static bool classof(const Type *T) {
1614    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1615  }
1616  static bool classof(const VectorType *) { return true; }
1617};
1618
1619/// ExtVectorType - Extended vector type. This type is created using
1620/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1621/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1622/// class enables syntactic extensions, like Vector Components for accessing
1623/// points, colors, and textures (modeled after OpenGL Shading Language).
1624class ExtVectorType : public VectorType {
1625  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1626    VectorType(ExtVector, vecType, nElements, canonType) {}
1627  friend class ASTContext;  // ASTContext creates these.
1628public:
1629  static int getPointAccessorIdx(char c) {
1630    switch (c) {
1631    default: return -1;
1632    case 'x': return 0;
1633    case 'y': return 1;
1634    case 'z': return 2;
1635    case 'w': return 3;
1636    }
1637  }
1638  static int getNumericAccessorIdx(char c) {
1639    switch (c) {
1640      default: return -1;
1641      case '0': return 0;
1642      case '1': return 1;
1643      case '2': return 2;
1644      case '3': return 3;
1645      case '4': return 4;
1646      case '5': return 5;
1647      case '6': return 6;
1648      case '7': return 7;
1649      case '8': return 8;
1650      case '9': return 9;
1651      case 'A':
1652      case 'a': return 10;
1653      case 'B':
1654      case 'b': return 11;
1655      case 'C':
1656      case 'c': return 12;
1657      case 'D':
1658      case 'd': return 13;
1659      case 'E':
1660      case 'e': return 14;
1661      case 'F':
1662      case 'f': return 15;
1663    }
1664  }
1665
1666  static int getAccessorIdx(char c) {
1667    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1668    return getNumericAccessorIdx(c);
1669  }
1670
1671  bool isAccessorWithinNumElements(char c) const {
1672    if (int idx = getAccessorIdx(c)+1)
1673      return unsigned(idx-1) < NumElements;
1674    return false;
1675  }
1676  bool isSugared() const { return false; }
1677  QualType desugar() const { return QualType(this, 0); }
1678
1679  static bool classof(const Type *T) {
1680    return T->getTypeClass() == ExtVector;
1681  }
1682  static bool classof(const ExtVectorType *) { return true; }
1683};
1684
1685/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1686/// class of FunctionNoProtoType and FunctionProtoType.
1687///
1688class FunctionType : public Type {
1689  /// SubClassData - This field is owned by the subclass, put here to pack
1690  /// tightly with the ivars in Type.
1691  bool SubClassData : 1;
1692
1693  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1694  /// other bitfields.
1695  /// The qualifiers are part of FunctionProtoType because...
1696  ///
1697  /// C++ 8.3.5p4: The return type, the parameter type list and the
1698  /// cv-qualifier-seq, [...], are part of the function type.
1699  ///
1700  unsigned TypeQuals : 3;
1701
1702  /// NoReturn - Indicates if the function type is attribute noreturn.
1703  unsigned NoReturn : 1;
1704
1705  // The type returned by the function.
1706  QualType ResultType;
1707protected:
1708  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1709               unsigned typeQuals, QualType Canonical, bool Dependent,
1710               bool noReturn = false)
1711    : Type(tc, Canonical, Dependent),
1712      SubClassData(SubclassInfo), TypeQuals(typeQuals), NoReturn(noReturn),
1713      ResultType(res) {}
1714  bool getSubClassData() const { return SubClassData; }
1715  unsigned getTypeQuals() const { return TypeQuals; }
1716public:
1717
1718  QualType getResultType() const { return ResultType; }
1719  bool getNoReturnAttr() const { return NoReturn; }
1720
1721  static bool classof(const Type *T) {
1722    return T->getTypeClass() == FunctionNoProto ||
1723           T->getTypeClass() == FunctionProto;
1724  }
1725  static bool classof(const FunctionType *) { return true; }
1726};
1727
1728/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1729/// no information available about its arguments.
1730class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1731  FunctionNoProtoType(QualType Result, QualType Canonical,
1732                      bool NoReturn = false)
1733    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1734                   /*Dependent=*/false, NoReturn) {}
1735  friend class ASTContext;  // ASTContext creates these.
1736public:
1737  // No additional state past what FunctionType provides.
1738
1739  bool isSugared() const { return false; }
1740  QualType desugar() const { return QualType(this, 0); }
1741
1742  void Profile(llvm::FoldingSetNodeID &ID) {
1743    Profile(ID, getResultType(), getNoReturnAttr());
1744  }
1745  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1746                      bool NoReturn) {
1747    ID.AddInteger(NoReturn);
1748    ID.AddPointer(ResultType.getAsOpaquePtr());
1749  }
1750
1751  static bool classof(const Type *T) {
1752    return T->getTypeClass() == FunctionNoProto;
1753  }
1754  static bool classof(const FunctionNoProtoType *) { return true; }
1755};
1756
1757/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1758/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1759/// arguments, not as having a single void argument. Such a type can have an
1760/// exception specification, but this specification is not part of the canonical
1761/// type.
1762class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1763  /// hasAnyDependentType - Determine whether there are any dependent
1764  /// types within the arguments passed in.
1765  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1766    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1767      if (ArgArray[Idx]->isDependentType())
1768    return true;
1769
1770    return false;
1771  }
1772
1773  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1774                    bool isVariadic, unsigned typeQuals, bool hasExs,
1775                    bool hasAnyExs, const QualType *ExArray,
1776                    unsigned numExs, QualType Canonical, bool NoReturn)
1777    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1778                   (Result->isDependentType() ||
1779                    hasAnyDependentType(ArgArray, numArgs)), NoReturn),
1780      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1781      AnyExceptionSpec(hasAnyExs) {
1782    // Fill in the trailing argument array.
1783    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1784    for (unsigned i = 0; i != numArgs; ++i)
1785      ArgInfo[i] = ArgArray[i];
1786    // Fill in the exception array.
1787    QualType *Ex = ArgInfo + numArgs;
1788    for (unsigned i = 0; i != numExs; ++i)
1789      Ex[i] = ExArray[i];
1790  }
1791
1792  /// NumArgs - The number of arguments this function has, not counting '...'.
1793  unsigned NumArgs : 20;
1794
1795  /// NumExceptions - The number of types in the exception spec, if any.
1796  unsigned NumExceptions : 10;
1797
1798  /// HasExceptionSpec - Whether this function has an exception spec at all.
1799  bool HasExceptionSpec : 1;
1800
1801  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1802  bool AnyExceptionSpec : 1;
1803
1804  /// ArgInfo - There is an variable size array after the class in memory that
1805  /// holds the argument types.
1806
1807  /// Exceptions - There is another variable size array after ArgInfo that
1808  /// holds the exception types.
1809
1810  friend class ASTContext;  // ASTContext creates these.
1811
1812public:
1813  unsigned getNumArgs() const { return NumArgs; }
1814  QualType getArgType(unsigned i) const {
1815    assert(i < NumArgs && "Invalid argument number!");
1816    return arg_type_begin()[i];
1817  }
1818
1819  bool hasExceptionSpec() const { return HasExceptionSpec; }
1820  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1821  unsigned getNumExceptions() const { return NumExceptions; }
1822  QualType getExceptionType(unsigned i) const {
1823    assert(i < NumExceptions && "Invalid exception number!");
1824    return exception_begin()[i];
1825  }
1826  bool hasEmptyExceptionSpec() const {
1827    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1828      getNumExceptions() == 0;
1829  }
1830
1831  bool isVariadic() const { return getSubClassData(); }
1832  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1833
1834  typedef const QualType *arg_type_iterator;
1835  arg_type_iterator arg_type_begin() const {
1836    return reinterpret_cast<const QualType *>(this+1);
1837  }
1838  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1839
1840  typedef const QualType *exception_iterator;
1841  exception_iterator exception_begin() const {
1842    // exceptions begin where arguments end
1843    return arg_type_end();
1844  }
1845  exception_iterator exception_end() const {
1846    return exception_begin() + NumExceptions;
1847  }
1848
1849  bool isSugared() const { return false; }
1850  QualType desugar() const { return QualType(this, 0); }
1851
1852  static bool classof(const Type *T) {
1853    return T->getTypeClass() == FunctionProto;
1854  }
1855  static bool classof(const FunctionProtoType *) { return true; }
1856
1857  void Profile(llvm::FoldingSetNodeID &ID);
1858  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1859                      arg_type_iterator ArgTys, unsigned NumArgs,
1860                      bool isVariadic, unsigned TypeQuals,
1861                      bool hasExceptionSpec, bool anyExceptionSpec,
1862                      unsigned NumExceptions, exception_iterator Exs,
1863                      bool NoReturn);
1864};
1865
1866
1867/// \brief Represents the dependent type named by a dependently-scoped
1868/// typename using declaration, e.g.
1869///   using typename Base<T>::foo;
1870/// Template instantiation turns these into the underlying type.
1871class UnresolvedUsingType : public Type {
1872  UnresolvedUsingTypenameDecl *Decl;
1873
1874  UnresolvedUsingType(UnresolvedUsingTypenameDecl *D)
1875    : Type(UnresolvedUsing, QualType(), true), Decl(D) {}
1876  friend class ASTContext; // ASTContext creates these.
1877public:
1878
1879  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
1880
1881  bool isSugared() const { return false; }
1882  QualType desugar() const { return QualType(this, 0); }
1883
1884  static bool classof(const Type *T) {
1885    return T->getTypeClass() == UnresolvedUsing;
1886  }
1887  static bool classof(const UnresolvedUsingType *) { return true; }
1888
1889  void Profile(llvm::FoldingSetNodeID &ID) {
1890    return Profile(ID, Decl);
1891  }
1892  static void Profile(llvm::FoldingSetNodeID &ID,
1893                      UnresolvedUsingTypenameDecl *D) {
1894    ID.AddPointer(D);
1895  }
1896};
1897
1898
1899class TypedefType : public Type {
1900  TypedefDecl *Decl;
1901protected:
1902  TypedefType(TypeClass tc, TypedefDecl *D, QualType can)
1903    : Type(tc, can, can->isDependentType()), Decl(D) {
1904    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1905  }
1906  friend class ASTContext;  // ASTContext creates these.
1907public:
1908
1909  TypedefDecl *getDecl() const { return Decl; }
1910
1911  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1912  /// potentially looking through *all* consecutive typedefs.  This returns the
1913  /// sum of the type qualifiers, so if you have:
1914  ///   typedef const int A;
1915  ///   typedef volatile A B;
1916  /// looking through the typedefs for B will give you "const volatile A".
1917  QualType LookThroughTypedefs() const;
1918
1919  bool isSugared() const { return true; }
1920  QualType desugar() const;
1921
1922  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
1923  static bool classof(const TypedefType *) { return true; }
1924};
1925
1926/// TypeOfExprType (GCC extension).
1927class TypeOfExprType : public Type {
1928  Expr *TOExpr;
1929
1930protected:
1931  TypeOfExprType(Expr *E, QualType can = QualType());
1932  friend class ASTContext;  // ASTContext creates these.
1933public:
1934  Expr *getUnderlyingExpr() const { return TOExpr; }
1935
1936  /// \brief Remove a single level of sugar.
1937  QualType desugar() const;
1938
1939  /// \brief Returns whether this type directly provides sugar.
1940  bool isSugared() const { return true; }
1941
1942  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
1943  static bool classof(const TypeOfExprType *) { return true; }
1944};
1945
1946/// Subclass of TypeOfExprType that is used for canonical, dependent
1947/// typeof(expr) types.
1948class DependentTypeOfExprType
1949  : public TypeOfExprType, public llvm::FoldingSetNode {
1950  ASTContext &Context;
1951
1952public:
1953  DependentTypeOfExprType(ASTContext &Context, Expr *E)
1954    : TypeOfExprType(E), Context(Context) { }
1955
1956  bool isSugared() const { return false; }
1957  QualType desugar() const { return QualType(this, 0); }
1958
1959  void Profile(llvm::FoldingSetNodeID &ID) {
1960    Profile(ID, Context, getUnderlyingExpr());
1961  }
1962
1963  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1964                      Expr *E);
1965};
1966
1967/// TypeOfType (GCC extension).
1968class TypeOfType : public Type {
1969  QualType TOType;
1970  TypeOfType(QualType T, QualType can)
1971    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
1972    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1973  }
1974  friend class ASTContext;  // ASTContext creates these.
1975public:
1976  QualType getUnderlyingType() const { return TOType; }
1977
1978  /// \brief Remove a single level of sugar.
1979  QualType desugar() const { return getUnderlyingType(); }
1980
1981  /// \brief Returns whether this type directly provides sugar.
1982  bool isSugared() const { return true; }
1983
1984  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
1985  static bool classof(const TypeOfType *) { return true; }
1986};
1987
1988/// DecltypeType (C++0x)
1989class DecltypeType : public Type {
1990  Expr *E;
1991
1992  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
1993  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
1994  // from it.
1995  QualType UnderlyingType;
1996
1997protected:
1998  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
1999  friend class ASTContext;  // ASTContext creates these.
2000public:
2001  Expr *getUnderlyingExpr() const { return E; }
2002  QualType getUnderlyingType() const { return UnderlyingType; }
2003
2004  /// \brief Remove a single level of sugar.
2005  QualType desugar() const { return getUnderlyingType(); }
2006
2007  /// \brief Returns whether this type directly provides sugar.
2008  bool isSugared() const { return !isDependentType(); }
2009
2010  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2011  static bool classof(const DecltypeType *) { return true; }
2012};
2013
2014/// Subclass of DecltypeType that is used for canonical, dependent
2015/// C++0x decltype types.
2016class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2017  ASTContext &Context;
2018
2019public:
2020  DependentDecltypeType(ASTContext &Context, Expr *E);
2021
2022  bool isSugared() const { return false; }
2023  QualType desugar() const { return QualType(this, 0); }
2024
2025  void Profile(llvm::FoldingSetNodeID &ID) {
2026    Profile(ID, Context, getUnderlyingExpr());
2027  }
2028
2029  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2030                      Expr *E);
2031};
2032
2033class TagType : public Type {
2034  /// Stores the TagDecl associated with this type. The decl will
2035  /// point to the TagDecl that actually defines the entity (or is a
2036  /// definition in progress), if there is such a definition. The
2037  /// single-bit value will be non-zero when this tag is in the
2038  /// process of being defined.
2039  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
2040  friend class ASTContext;
2041  friend class TagDecl;
2042
2043protected:
2044  TagType(TypeClass TC, TagDecl *D, QualType can);
2045
2046public:
2047  TagDecl *getDecl() const { return decl.getPointer(); }
2048
2049  /// @brief Determines whether this type is in the process of being
2050  /// defined.
2051  bool isBeingDefined() const { return decl.getInt(); }
2052  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
2053
2054  static bool classof(const Type *T) {
2055    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2056  }
2057  static bool classof(const TagType *) { return true; }
2058  static bool classof(const RecordType *) { return true; }
2059  static bool classof(const EnumType *) { return true; }
2060};
2061
2062/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2063/// to detect TagType objects of structs/unions/classes.
2064class RecordType : public TagType {
2065protected:
2066  explicit RecordType(RecordDecl *D)
2067    : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { }
2068  explicit RecordType(TypeClass TC, RecordDecl *D)
2069    : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { }
2070  friend class ASTContext;   // ASTContext creates these.
2071public:
2072
2073  RecordDecl *getDecl() const {
2074    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2075  }
2076
2077  // FIXME: This predicate is a helper to QualType/Type. It needs to
2078  // recursively check all fields for const-ness. If any field is declared
2079  // const, it needs to return false.
2080  bool hasConstFields() const { return false; }
2081
2082  // FIXME: RecordType needs to check when it is created that all fields are in
2083  // the same address space, and return that.
2084  unsigned getAddressSpace() const { return 0; }
2085
2086  bool isSugared() const { return false; }
2087  QualType desugar() const { return QualType(this, 0); }
2088
2089  static bool classof(const TagType *T);
2090  static bool classof(const Type *T) {
2091    return isa<TagType>(T) && classof(cast<TagType>(T));
2092  }
2093  static bool classof(const RecordType *) { return true; }
2094};
2095
2096/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2097/// to detect TagType objects of enums.
2098class EnumType : public TagType {
2099  explicit EnumType(EnumDecl *D)
2100    : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { }
2101  friend class ASTContext;   // ASTContext creates these.
2102public:
2103
2104  EnumDecl *getDecl() const {
2105    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2106  }
2107
2108  bool isSugared() const { return false; }
2109  QualType desugar() const { return QualType(this, 0); }
2110
2111  static bool classof(const TagType *T);
2112  static bool classof(const Type *T) {
2113    return isa<TagType>(T) && classof(cast<TagType>(T));
2114  }
2115  static bool classof(const EnumType *) { return true; }
2116};
2117
2118/// ElaboratedType - A non-canonical type used to represents uses of
2119/// elaborated type specifiers in C++.  For example:
2120///
2121///   void foo(union MyUnion);
2122///            ^^^^^^^^^^^^^
2123///
2124/// At the moment, for efficiency we do not create elaborated types in
2125/// C, since outside of typedefs all references to structs would
2126/// necessarily be elaborated.
2127class ElaboratedType : public Type, public llvm::FoldingSetNode {
2128public:
2129  enum TagKind {
2130    TK_struct,
2131    TK_union,
2132    TK_class,
2133    TK_enum
2134  };
2135
2136private:
2137  /// The tag that was used in this elaborated type specifier.
2138  TagKind Tag;
2139
2140  /// The underlying type.
2141  QualType UnderlyingType;
2142
2143  explicit ElaboratedType(QualType Ty, TagKind Tag, QualType Canon)
2144    : Type(Elaborated, Canon, Canon->isDependentType()),
2145      Tag(Tag), UnderlyingType(Ty) { }
2146  friend class ASTContext;   // ASTContext creates these.
2147
2148public:
2149  TagKind getTagKind() const { return Tag; }
2150  QualType getUnderlyingType() const { return UnderlyingType; }
2151
2152  /// \brief Remove a single level of sugar.
2153  QualType desugar() const { return getUnderlyingType(); }
2154
2155  /// \brief Returns whether this type directly provides sugar.
2156  bool isSugared() const { return true; }
2157
2158  static const char *getNameForTagKind(TagKind Kind) {
2159    switch (Kind) {
2160    default: assert(0 && "Unknown TagKind!");
2161    case TK_struct: return "struct";
2162    case TK_union:  return "union";
2163    case TK_class:  return "class";
2164    case TK_enum:   return "enum";
2165    }
2166  }
2167
2168  void Profile(llvm::FoldingSetNodeID &ID) {
2169    Profile(ID, getUnderlyingType(), getTagKind());
2170  }
2171  static void Profile(llvm::FoldingSetNodeID &ID, QualType T, TagKind Tag) {
2172    ID.AddPointer(T.getAsOpaquePtr());
2173    ID.AddInteger(Tag);
2174  }
2175
2176  static bool classof(const ElaboratedType*) { return true; }
2177  static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
2178};
2179
2180class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2181  unsigned Depth : 15;
2182  unsigned Index : 16;
2183  unsigned ParameterPack : 1;
2184  IdentifierInfo *Name;
2185
2186  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2187                       QualType Canon)
2188    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2189      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2190
2191  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2192    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2193      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2194
2195  friend class ASTContext;  // ASTContext creates these
2196
2197public:
2198  unsigned getDepth() const { return Depth; }
2199  unsigned getIndex() const { return Index; }
2200  bool isParameterPack() const { return ParameterPack; }
2201  IdentifierInfo *getName() const { return Name; }
2202
2203  bool isSugared() const { return false; }
2204  QualType desugar() const { return QualType(this, 0); }
2205
2206  void Profile(llvm::FoldingSetNodeID &ID) {
2207    Profile(ID, Depth, Index, ParameterPack, Name);
2208  }
2209
2210  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2211                      unsigned Index, bool ParameterPack,
2212                      IdentifierInfo *Name) {
2213    ID.AddInteger(Depth);
2214    ID.AddInteger(Index);
2215    ID.AddBoolean(ParameterPack);
2216    ID.AddPointer(Name);
2217  }
2218
2219  static bool classof(const Type *T) {
2220    return T->getTypeClass() == TemplateTypeParm;
2221  }
2222  static bool classof(const TemplateTypeParmType *T) { return true; }
2223};
2224
2225/// \brief Represents the result of substituting a type for a template
2226/// type parameter.
2227///
2228/// Within an instantiated template, all template type parameters have
2229/// been replaced with these.  They are used solely to record that a
2230/// type was originally written as a template type parameter;
2231/// therefore they are never canonical.
2232class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2233  // The original type parameter.
2234  const TemplateTypeParmType *Replaced;
2235
2236  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2237    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType()),
2238      Replaced(Param) { }
2239
2240  friend class ASTContext;
2241
2242public:
2243  IdentifierInfo *getName() const { return Replaced->getName(); }
2244
2245  /// Gets the template parameter that was substituted for.
2246  const TemplateTypeParmType *getReplacedParameter() const {
2247    return Replaced;
2248  }
2249
2250  /// Gets the type that was substituted for the template
2251  /// parameter.
2252  QualType getReplacementType() const {
2253    return getCanonicalTypeInternal();
2254  }
2255
2256  bool isSugared() const { return true; }
2257  QualType desugar() const { return getReplacementType(); }
2258
2259  void Profile(llvm::FoldingSetNodeID &ID) {
2260    Profile(ID, getReplacedParameter(), getReplacementType());
2261  }
2262  static void Profile(llvm::FoldingSetNodeID &ID,
2263                      const TemplateTypeParmType *Replaced,
2264                      QualType Replacement) {
2265    ID.AddPointer(Replaced);
2266    ID.AddPointer(Replacement.getAsOpaquePtr());
2267  }
2268
2269  static bool classof(const Type *T) {
2270    return T->getTypeClass() == SubstTemplateTypeParm;
2271  }
2272  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2273};
2274
2275/// \brief Represents the type of a template specialization as written
2276/// in the source code.
2277///
2278/// Template specialization types represent the syntactic form of a
2279/// template-id that refers to a type, e.g., @c vector<int>. Some
2280/// template specialization types are syntactic sugar, whose canonical
2281/// type will point to some other type node that represents the
2282/// instantiation or class template specialization. For example, a
2283/// class template specialization type of @c vector<int> will refer to
2284/// a tag type for the instantiation
2285/// @c std::vector<int, std::allocator<int>>.
2286///
2287/// Other template specialization types, for which the template name
2288/// is dependent, may be canonical types. These types are always
2289/// dependent.
2290class TemplateSpecializationType
2291  : public Type, public llvm::FoldingSetNode {
2292
2293  // FIXME: Currently needed for profiling expressions; can we avoid this?
2294  ASTContext &Context;
2295
2296    /// \brief The name of the template being specialized.
2297  TemplateName Template;
2298
2299  /// \brief - The number of template arguments named in this class
2300  /// template specialization.
2301  unsigned NumArgs;
2302
2303  TemplateSpecializationType(ASTContext &Context,
2304                             TemplateName T,
2305                             const TemplateArgument *Args,
2306                             unsigned NumArgs, QualType Canon);
2307
2308  virtual void Destroy(ASTContext& C);
2309
2310  friend class ASTContext;  // ASTContext creates these
2311
2312public:
2313  /// \brief Determine whether any of the given template arguments are
2314  /// dependent.
2315  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2316                                            unsigned NumArgs);
2317
2318  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2319                                            unsigned NumArgs);
2320
2321  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
2322
2323  /// \brief Print a template argument list, including the '<' and '>'
2324  /// enclosing the template arguments.
2325  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2326                                               unsigned NumArgs,
2327                                               const PrintingPolicy &Policy);
2328
2329  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2330                                               unsigned NumArgs,
2331                                               const PrintingPolicy &Policy);
2332
2333  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
2334                                               const PrintingPolicy &Policy);
2335
2336  typedef const TemplateArgument * iterator;
2337
2338  iterator begin() const { return getArgs(); }
2339  iterator end() const;
2340
2341  /// \brief Retrieve the name of the template that we are specializing.
2342  TemplateName getTemplateName() const { return Template; }
2343
2344  /// \brief Retrieve the template arguments.
2345  const TemplateArgument *getArgs() const {
2346    return reinterpret_cast<const TemplateArgument *>(this + 1);
2347  }
2348
2349  /// \brief Retrieve the number of template arguments.
2350  unsigned getNumArgs() const { return NumArgs; }
2351
2352  /// \brief Retrieve a specific template argument as a type.
2353  /// \precondition @c isArgType(Arg)
2354  const TemplateArgument &getArg(unsigned Idx) const;
2355
2356  bool isSugared() const { return !isDependentType(); }
2357  QualType desugar() const { return getCanonicalTypeInternal(); }
2358
2359  void Profile(llvm::FoldingSetNodeID &ID) {
2360    Profile(ID, Template, getArgs(), NumArgs, Context);
2361  }
2362
2363  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2364                      const TemplateArgument *Args, unsigned NumArgs,
2365                      ASTContext &Context);
2366
2367  static bool classof(const Type *T) {
2368    return T->getTypeClass() == TemplateSpecialization;
2369  }
2370  static bool classof(const TemplateSpecializationType *T) { return true; }
2371};
2372
2373/// \brief Represents a type that was referred to via a qualified
2374/// name, e.g., N::M::type.
2375///
2376/// This type is used to keep track of a type name as written in the
2377/// source code, including any nested-name-specifiers. The type itself
2378/// is always "sugar", used to express what was written in the source
2379/// code but containing no additional semantic information.
2380class QualifiedNameType : public Type, public llvm::FoldingSetNode {
2381  /// \brief The nested name specifier containing the qualifier.
2382  NestedNameSpecifier *NNS;
2383
2384  /// \brief The type that this qualified name refers to.
2385  QualType NamedType;
2386
2387  QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType,
2388                    QualType CanonType)
2389    : Type(QualifiedName, CanonType, NamedType->isDependentType()),
2390      NNS(NNS), NamedType(NamedType) { }
2391
2392  friend class ASTContext;  // ASTContext creates these
2393
2394public:
2395  /// \brief Retrieve the qualification on this type.
2396  NestedNameSpecifier *getQualifier() const { return NNS; }
2397
2398  /// \brief Retrieve the type named by the qualified-id.
2399  QualType getNamedType() const { return NamedType; }
2400
2401  /// \brief Remove a single level of sugar.
2402  QualType desugar() const { return getNamedType(); }
2403
2404  /// \brief Returns whether this type directly provides sugar.
2405  bool isSugared() const { return true; }
2406
2407  void Profile(llvm::FoldingSetNodeID &ID) {
2408    Profile(ID, NNS, NamedType);
2409  }
2410
2411  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2412                      QualType NamedType) {
2413    ID.AddPointer(NNS);
2414    NamedType.Profile(ID);
2415  }
2416
2417  static bool classof(const Type *T) {
2418    return T->getTypeClass() == QualifiedName;
2419  }
2420  static bool classof(const QualifiedNameType *T) { return true; }
2421};
2422
2423/// \brief Represents a 'typename' specifier that names a type within
2424/// a dependent type, e.g., "typename T::type".
2425///
2426/// TypenameType has a very similar structure to QualifiedNameType,
2427/// which also involves a nested-name-specifier following by a type,
2428/// and (FIXME!) both can even be prefixed by the 'typename'
2429/// keyword. However, the two types serve very different roles:
2430/// QualifiedNameType is a non-semantic type that serves only as sugar
2431/// to show how a particular type was written in the source
2432/// code. TypenameType, on the other hand, only occurs when the
2433/// nested-name-specifier is dependent, such that we cannot resolve
2434/// the actual type until after instantiation.
2435class TypenameType : public Type, public llvm::FoldingSetNode {
2436  /// \brief The nested name specifier containing the qualifier.
2437  NestedNameSpecifier *NNS;
2438
2439  typedef llvm::PointerUnion<const IdentifierInfo *,
2440                             const TemplateSpecializationType *> NameType;
2441
2442  /// \brief The type that this typename specifier refers to.
2443  NameType Name;
2444
2445  TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2446               QualType CanonType)
2447    : Type(Typename, CanonType, true), NNS(NNS), Name(Name) {
2448    assert(NNS->isDependent() &&
2449           "TypenameType requires a dependent nested-name-specifier");
2450  }
2451
2452  TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty,
2453               QualType CanonType)
2454    : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) {
2455    assert(NNS->isDependent() &&
2456           "TypenameType requires a dependent nested-name-specifier");
2457  }
2458
2459  friend class ASTContext;  // ASTContext creates these
2460
2461public:
2462  /// \brief Retrieve the qualification on this type.
2463  NestedNameSpecifier *getQualifier() const { return NNS; }
2464
2465  /// \brief Retrieve the type named by the typename specifier as an
2466  /// identifier.
2467  ///
2468  /// This routine will return a non-NULL identifier pointer when the
2469  /// form of the original typename was terminated by an identifier,
2470  /// e.g., "typename T::type".
2471  const IdentifierInfo *getIdentifier() const {
2472    return Name.dyn_cast<const IdentifierInfo *>();
2473  }
2474
2475  /// \brief Retrieve the type named by the typename specifier as a
2476  /// type specialization.
2477  const TemplateSpecializationType *getTemplateId() const {
2478    return Name.dyn_cast<const TemplateSpecializationType *>();
2479  }
2480
2481  bool isSugared() const { return false; }
2482  QualType desugar() const { return QualType(this, 0); }
2483
2484  void Profile(llvm::FoldingSetNodeID &ID) {
2485    Profile(ID, NNS, Name);
2486  }
2487
2488  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2489                      NameType Name) {
2490    ID.AddPointer(NNS);
2491    ID.AddPointer(Name.getOpaqueValue());
2492  }
2493
2494  static bool classof(const Type *T) {
2495    return T->getTypeClass() == Typename;
2496  }
2497  static bool classof(const TypenameType *T) { return true; }
2498};
2499
2500/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2501/// object oriented design.  They basically correspond to C++ classes.  There
2502/// are two kinds of interface types, normal interfaces like "NSString" and
2503/// qualified interfaces, which are qualified with a protocol list like
2504/// "NSString<NSCopyable, NSAmazing>".
2505class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
2506  ObjCInterfaceDecl *Decl;
2507
2508  // List of protocols for this protocol conforming object type
2509  // List is sorted on protocol name. No protocol is enterred more than once.
2510  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
2511
2512  ObjCInterfaceType(QualType Canonical, ObjCInterfaceDecl *D,
2513                    ObjCProtocolDecl **Protos, unsigned NumP) :
2514    Type(ObjCInterface, Canonical, /*Dependent=*/false),
2515    Decl(D), Protocols(Protos, Protos+NumP) { }
2516  friend class ASTContext;  // ASTContext creates these.
2517public:
2518  ObjCInterfaceDecl *getDecl() const { return Decl; }
2519
2520  /// getNumProtocols - Return the number of qualifying protocols in this
2521  /// interface type, or 0 if there are none.
2522  unsigned getNumProtocols() const { return Protocols.size(); }
2523
2524  /// qual_iterator and friends: this provides access to the (potentially empty)
2525  /// list of protocols qualifying this interface.
2526  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2527  qual_iterator qual_begin() const { return Protocols.begin(); }
2528  qual_iterator qual_end() const   { return Protocols.end(); }
2529  bool qual_empty() const { return Protocols.size() == 0; }
2530
2531  bool isSugared() const { return false; }
2532  QualType desugar() const { return QualType(this, 0); }
2533
2534  void Profile(llvm::FoldingSetNodeID &ID);
2535  static void Profile(llvm::FoldingSetNodeID &ID,
2536                      const ObjCInterfaceDecl *Decl,
2537                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2538
2539  static bool classof(const Type *T) {
2540    return T->getTypeClass() == ObjCInterface;
2541  }
2542  static bool classof(const ObjCInterfaceType *) { return true; }
2543};
2544
2545/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2546/// and 'Interface <p> *'.
2547///
2548/// Duplicate protocols are removed and protocol list is canonicalized to be in
2549/// alphabetical order.
2550class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2551  QualType PointeeType; // A builtin or interface type.
2552
2553  // List of protocols for this protocol conforming object type
2554  // List is sorted on protocol name. No protocol is entered more than once.
2555  llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols;
2556
2557  ObjCObjectPointerType(QualType Canonical, QualType T,
2558                        ObjCProtocolDecl **Protos, unsigned NumP) :
2559    Type(ObjCObjectPointer, Canonical, /*Dependent=*/false),
2560    PointeeType(T), Protocols(Protos, Protos+NumP) { }
2561  friend class ASTContext;  // ASTContext creates these.
2562
2563public:
2564  // Get the pointee type. Pointee will either be:
2565  // - a built-in type (for 'id' and 'Class').
2566  // - an interface type (for user-defined types).
2567  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2568  //   For example: typedef NSObject T; T *var;
2569  QualType getPointeeType() const { return PointeeType; }
2570
2571  const ObjCInterfaceType *getInterfaceType() const {
2572    return PointeeType->getAs<ObjCInterfaceType>();
2573  }
2574  /// getInterfaceDecl - returns an interface decl for user-defined types.
2575  ObjCInterfaceDecl *getInterfaceDecl() const {
2576    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2577  }
2578  /// isObjCIdType - true for "id".
2579  bool isObjCIdType() const {
2580    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2581           !Protocols.size();
2582  }
2583  /// isObjCClassType - true for "Class".
2584  bool isObjCClassType() const {
2585    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2586           !Protocols.size();
2587  }
2588
2589  /// isObjCQualifiedIdType - true for "id <p>".
2590  bool isObjCQualifiedIdType() const {
2591    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2592           Protocols.size();
2593  }
2594  /// isObjCQualifiedClassType - true for "Class <p>".
2595  bool isObjCQualifiedClassType() const {
2596    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2597           Protocols.size();
2598  }
2599  /// qual_iterator and friends: this provides access to the (potentially empty)
2600  /// list of protocols qualifying this interface.
2601  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2602
2603  qual_iterator qual_begin() const { return Protocols.begin(); }
2604  qual_iterator qual_end() const   { return Protocols.end(); }
2605  bool qual_empty() const { return Protocols.size() == 0; }
2606
2607  /// getNumProtocols - Return the number of qualifying protocols in this
2608  /// interface type, or 0 if there are none.
2609  unsigned getNumProtocols() const { return Protocols.size(); }
2610
2611  bool isSugared() const { return false; }
2612  QualType desugar() const { return QualType(this, 0); }
2613
2614  void Profile(llvm::FoldingSetNodeID &ID);
2615  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2616                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2617  static bool classof(const Type *T) {
2618    return T->getTypeClass() == ObjCObjectPointer;
2619  }
2620  static bool classof(const ObjCObjectPointerType *) { return true; }
2621};
2622
2623/// A qualifier set is used to build a set of qualifiers.
2624class QualifierCollector : public Qualifiers {
2625  ASTContext *Context;
2626
2627public:
2628  QualifierCollector(Qualifiers Qs = Qualifiers())
2629    : Qualifiers(Qs), Context(0) {}
2630  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
2631    : Qualifiers(Qs), Context(&Context) {}
2632
2633  void setContext(ASTContext &C) { Context = &C; }
2634
2635  /// Collect any qualifiers on the given type and return an
2636  /// unqualified type.
2637  const Type *strip(QualType QT) {
2638    addFastQualifiers(QT.getLocalFastQualifiers());
2639    if (QT.hasLocalNonFastQualifiers()) {
2640      const ExtQuals *EQ = QT.getExtQualsUnsafe();
2641      Context = &EQ->getContext();
2642      addQualifiers(EQ->getQualifiers());
2643      return EQ->getBaseType();
2644    }
2645    return QT.getTypePtrUnsafe();
2646  }
2647
2648  /// Apply the collected qualifiers to the given type.
2649  QualType apply(QualType QT) const;
2650
2651  /// Apply the collected qualifiers to the given type.
2652  QualType apply(const Type* T) const;
2653
2654};
2655
2656
2657// Inline function definitions.
2658
2659inline bool QualType::isCanonical() const {
2660  const Type *T = getTypePtr();
2661  if (hasLocalQualifiers())
2662    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
2663  return T->isCanonicalUnqualified();
2664}
2665
2666inline bool QualType::isCanonicalAsParam() const {
2667  if (hasLocalQualifiers()) return false;
2668  const Type *T = getTypePtr();
2669  return T->isCanonicalUnqualified() &&
2670           !isa<FunctionType>(T) && !isa<ArrayType>(T);
2671}
2672
2673inline bool QualType::isConstQualified() const {
2674  return isLocalConstQualified() ||
2675              getTypePtr()->getCanonicalTypeInternal().isLocalConstQualified();
2676}
2677
2678inline bool QualType::isRestrictQualified() const {
2679  return isLocalRestrictQualified() ||
2680            getTypePtr()->getCanonicalTypeInternal().isLocalRestrictQualified();
2681}
2682
2683
2684inline bool QualType::isVolatileQualified() const {
2685  return isLocalVolatileQualified() ||
2686  getTypePtr()->getCanonicalTypeInternal().isLocalVolatileQualified();
2687}
2688
2689inline bool QualType::hasQualifiers() const {
2690  return hasLocalQualifiers() ||
2691                  getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers();
2692}
2693
2694inline Qualifiers QualType::getQualifiers() const {
2695  Qualifiers Quals = getLocalQualifiers();
2696  Quals.addQualifiers(
2697                 getTypePtr()->getCanonicalTypeInternal().getLocalQualifiers());
2698  return Quals;
2699}
2700
2701inline unsigned QualType::getCVRQualifiers() const {
2702  return getLocalCVRQualifiers() |
2703              getTypePtr()->getCanonicalTypeInternal().getLocalCVRQualifiers();
2704}
2705
2706inline void QualType::removeConst() {
2707  removeFastQualifiers(Qualifiers::Const);
2708}
2709
2710inline void QualType::removeRestrict() {
2711  removeFastQualifiers(Qualifiers::Restrict);
2712}
2713
2714inline void QualType::removeVolatile() {
2715  QualifierCollector Qc;
2716  const Type *Ty = Qc.strip(*this);
2717  if (Qc.hasVolatile()) {
2718    Qc.removeVolatile();
2719    *this = Qc.apply(Ty);
2720  }
2721}
2722
2723inline void QualType::removeCVRQualifiers(unsigned Mask) {
2724  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
2725
2726  // Fast path: we don't need to touch the slow qualifiers.
2727  if (!(Mask & ~Qualifiers::FastMask)) {
2728    removeFastQualifiers(Mask);
2729    return;
2730  }
2731
2732  QualifierCollector Qc;
2733  const Type *Ty = Qc.strip(*this);
2734  Qc.removeCVRQualifiers(Mask);
2735  *this = Qc.apply(Ty);
2736}
2737
2738/// getAddressSpace - Return the address space of this type.
2739inline unsigned QualType::getAddressSpace() const {
2740  if (hasLocalNonFastQualifiers()) {
2741    const ExtQuals *EQ = getExtQualsUnsafe();
2742    if (EQ->hasAddressSpace())
2743      return EQ->getAddressSpace();
2744  }
2745
2746  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2747  if (CT.hasLocalNonFastQualifiers()) {
2748    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2749    if (EQ->hasAddressSpace())
2750      return EQ->getAddressSpace();
2751  }
2752
2753  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2754    return AT->getElementType().getAddressSpace();
2755  if (const RecordType *RT = dyn_cast<RecordType>(CT))
2756    return RT->getAddressSpace();
2757  return 0;
2758}
2759
2760/// getObjCGCAttr - Return the gc attribute of this type.
2761inline Qualifiers::GC QualType::getObjCGCAttr() const {
2762  if (hasLocalNonFastQualifiers()) {
2763    const ExtQuals *EQ = getExtQualsUnsafe();
2764    if (EQ->hasObjCGCAttr())
2765      return EQ->getObjCGCAttr();
2766  }
2767
2768  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2769  if (CT.hasLocalNonFastQualifiers()) {
2770    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2771    if (EQ->hasObjCGCAttr())
2772      return EQ->getObjCGCAttr();
2773  }
2774
2775  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2776      return AT->getElementType().getObjCGCAttr();
2777  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
2778    return PT->getPointeeType().getObjCGCAttr();
2779  // We most look at all pointer types, not just pointer to interface types.
2780  if (const PointerType *PT = CT->getAs<PointerType>())
2781    return PT->getPointeeType().getObjCGCAttr();
2782  return Qualifiers::GCNone;
2783}
2784
2785  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
2786  /// false otherwise.
2787inline bool QualType::getNoReturnAttr() const {
2788  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2789  if (const PointerType *PT = getTypePtr()->getAs<PointerType>()) {
2790    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
2791      return FT->getNoReturnAttr();
2792  } else if (const FunctionType *FT = getTypePtr()->getAs<FunctionType>())
2793    return FT->getNoReturnAttr();
2794
2795  return false;
2796}
2797
2798/// isMoreQualifiedThan - Determine whether this type is more
2799/// qualified than the Other type. For example, "const volatile int"
2800/// is more qualified than "const int", "volatile int", and
2801/// "int". However, it is not more qualified than "const volatile
2802/// int".
2803inline bool QualType::isMoreQualifiedThan(QualType Other) const {
2804  // FIXME: work on arbitrary qualifiers
2805  unsigned MyQuals = this->getCVRQualifiers();
2806  unsigned OtherQuals = Other.getCVRQualifiers();
2807  if (getAddressSpace() != Other.getAddressSpace())
2808    return false;
2809  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
2810}
2811
2812/// isAtLeastAsQualifiedAs - Determine whether this type is at last
2813/// as qualified as the Other type. For example, "const volatile
2814/// int" is at least as qualified as "const int", "volatile int",
2815/// "int", and "const volatile int".
2816inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
2817  // FIXME: work on arbitrary qualifiers
2818  unsigned MyQuals = this->getCVRQualifiers();
2819  unsigned OtherQuals = Other.getCVRQualifiers();
2820  if (getAddressSpace() != Other.getAddressSpace())
2821    return false;
2822  return (MyQuals | OtherQuals) == MyQuals;
2823}
2824
2825/// getNonReferenceType - If Type is a reference type (e.g., const
2826/// int&), returns the type that the reference refers to ("const
2827/// int"). Otherwise, returns the type itself. This routine is used
2828/// throughout Sema to implement C++ 5p6:
2829///
2830///   If an expression initially has the type "reference to T" (8.3.2,
2831///   8.5.3), the type is adjusted to "T" prior to any further
2832///   analysis, the expression designates the object or function
2833///   denoted by the reference, and the expression is an lvalue.
2834inline QualType QualType::getNonReferenceType() const {
2835  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
2836    return RefType->getPointeeType();
2837  else
2838    return *this;
2839}
2840
2841inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
2842  if (const PointerType *PT = getAs<PointerType>())
2843    return PT->getPointeeType()->getAs<ObjCInterfaceType>();
2844  return 0;
2845}
2846
2847inline bool Type::isFunctionType() const {
2848  return isa<FunctionType>(CanonicalType);
2849}
2850inline bool Type::isPointerType() const {
2851  return isa<PointerType>(CanonicalType);
2852}
2853inline bool Type::isAnyPointerType() const {
2854  return isPointerType() || isObjCObjectPointerType();
2855}
2856inline bool Type::isBlockPointerType() const {
2857  return isa<BlockPointerType>(CanonicalType);
2858}
2859inline bool Type::isReferenceType() const {
2860  return isa<ReferenceType>(CanonicalType);
2861}
2862inline bool Type::isLValueReferenceType() const {
2863  return isa<LValueReferenceType>(CanonicalType);
2864}
2865inline bool Type::isRValueReferenceType() const {
2866  return isa<RValueReferenceType>(CanonicalType);
2867}
2868inline bool Type::isFunctionPointerType() const {
2869  if (const PointerType* T = getAs<PointerType>())
2870    return T->getPointeeType()->isFunctionType();
2871  else
2872    return false;
2873}
2874inline bool Type::isMemberPointerType() const {
2875  return isa<MemberPointerType>(CanonicalType);
2876}
2877inline bool Type::isMemberFunctionPointerType() const {
2878  if (const MemberPointerType* T = getAs<MemberPointerType>())
2879    return T->getPointeeType()->isFunctionType();
2880  else
2881    return false;
2882}
2883inline bool Type::isArrayType() const {
2884  return isa<ArrayType>(CanonicalType);
2885}
2886inline bool Type::isConstantArrayType() const {
2887  return isa<ConstantArrayType>(CanonicalType);
2888}
2889inline bool Type::isIncompleteArrayType() const {
2890  return isa<IncompleteArrayType>(CanonicalType);
2891}
2892inline bool Type::isVariableArrayType() const {
2893  return isa<VariableArrayType>(CanonicalType);
2894}
2895inline bool Type::isDependentSizedArrayType() const {
2896  return isa<DependentSizedArrayType>(CanonicalType);
2897}
2898inline bool Type::isRecordType() const {
2899  return isa<RecordType>(CanonicalType);
2900}
2901inline bool Type::isAnyComplexType() const {
2902  return isa<ComplexType>(CanonicalType);
2903}
2904inline bool Type::isVectorType() const {
2905  return isa<VectorType>(CanonicalType);
2906}
2907inline bool Type::isExtVectorType() const {
2908  return isa<ExtVectorType>(CanonicalType);
2909}
2910inline bool Type::isObjCObjectPointerType() const {
2911  return isa<ObjCObjectPointerType>(CanonicalType);
2912}
2913inline bool Type::isObjCInterfaceType() const {
2914  return isa<ObjCInterfaceType>(CanonicalType);
2915}
2916inline bool Type::isObjCQualifiedIdType() const {
2917  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2918    return OPT->isObjCQualifiedIdType();
2919  return false;
2920}
2921inline bool Type::isObjCQualifiedClassType() const {
2922  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2923    return OPT->isObjCQualifiedClassType();
2924  return false;
2925}
2926inline bool Type::isObjCIdType() const {
2927  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2928    return OPT->isObjCIdType();
2929  return false;
2930}
2931inline bool Type::isObjCClassType() const {
2932  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2933    return OPT->isObjCClassType();
2934  return false;
2935}
2936inline bool Type::isObjCSelType() const {
2937  if (const PointerType *OPT = getAs<PointerType>())
2938    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
2939  return false;
2940}
2941inline bool Type::isObjCBuiltinType() const {
2942  return isObjCIdType() || isObjCClassType() || isObjCSelType();
2943}
2944inline bool Type::isTemplateTypeParmType() const {
2945  return isa<TemplateTypeParmType>(CanonicalType);
2946}
2947
2948inline bool Type::isSpecificBuiltinType(unsigned K) const {
2949  if (const BuiltinType *BT = getAs<BuiltinType>())
2950    if (BT->getKind() == (BuiltinType::Kind) K)
2951      return true;
2952  return false;
2953}
2954
2955/// \brief Determines whether this is a type for which one can define
2956/// an overloaded operator.
2957inline bool Type::isOverloadableType() const {
2958  return isDependentType() || isRecordType() || isEnumeralType();
2959}
2960
2961inline bool Type::hasPointerRepresentation() const {
2962  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
2963          isObjCInterfaceType() || isObjCObjectPointerType() ||
2964          isObjCQualifiedInterfaceType() || isNullPtrType());
2965}
2966
2967inline bool Type::hasObjCPointerRepresentation() const {
2968  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
2969          isObjCQualifiedInterfaceType());
2970}
2971
2972/// Insertion operator for diagnostics.  This allows sending QualType's into a
2973/// diagnostic with <<.
2974inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2975                                           QualType T) {
2976  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
2977                  Diagnostic::ak_qualtype);
2978  return DB;
2979}
2980
2981// Helper class template that is used by Type::getAs to ensure that one does
2982// not try to look through a qualified type to get to an array type.
2983template<typename T,
2984         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
2985                             llvm::is_base_of<ArrayType, T>::value)>
2986struct ArrayType_cannot_be_used_with_getAs { };
2987
2988template<typename T>
2989struct ArrayType_cannot_be_used_with_getAs<T, true>;
2990
2991/// Member-template getAs<specific type>'.
2992template <typename T> const T *Type::getAs() const {
2993  ArrayType_cannot_be_used_with_getAs<T> at;
2994  (void)at;
2995
2996  // If this is directly a T type, return it.
2997  if (const T *Ty = dyn_cast<T>(this))
2998    return Ty;
2999
3000  // If the canonical form of this type isn't the right kind, reject it.
3001  if (!isa<T>(CanonicalType))
3002    return 0;
3003
3004  // If this is a typedef for the type, strip the typedef off without
3005  // losing all typedef information.
3006  return cast<T>(getUnqualifiedDesugaredType());
3007}
3008
3009}  // end namespace clang
3010
3011#endif
3012