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