Type.cpp revision 99eef4a6d3632a78155e7639a9f91d10b33e8218
1//===--- Type.cpp - Type representation and manipulation ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements type-related functionality.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Type.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace clang;
24
25bool QualType::isConstant(ASTContext &Ctx) const {
26  if (isConstQualified())
27    return true;
28
29  if (getTypePtr()->isArrayType())
30    return Ctx.getAsArrayType(*this)->getElementType().isConstant(Ctx);
31
32  return false;
33}
34
35void Type::Destroy(ASTContext& C) {
36  this->~Type();
37  C.Deallocate(this);
38}
39
40void ConstantArrayWithExprType::Destroy(ASTContext& C) {
41  // FIXME: destruction of SizeExpr commented out due to resource contention.
42  // SizeExpr->Destroy(C);
43  // See FIXME in SemaDecl.cpp:1536: if we were able to either steal
44  // or clone the SizeExpr there, then here we could freely delete it.
45  // Since we do not know how to steal or clone, we keep a pointer to
46  // a shared resource, but we cannot free it.
47  // (There probably is a trivial solution ... for people knowing clang!).
48  this->~ConstantArrayWithExprType();
49  C.Deallocate(this);
50}
51
52void VariableArrayType::Destroy(ASTContext& C) {
53  if (SizeExpr)
54    SizeExpr->Destroy(C);
55  this->~VariableArrayType();
56  C.Deallocate(this);
57}
58
59void DependentSizedArrayType::Destroy(ASTContext& C) {
60  // FIXME: Resource contention like in ConstantArrayWithExprType ?
61  // May crash, depending on platform or a particular build.
62  // SizeExpr->Destroy(C);
63  this->~DependentSizedArrayType();
64  C.Deallocate(this);
65}
66
67void DependentSizedExtVectorType::Destroy(ASTContext& C) {
68  // FIXME: Deallocate size expression, once we're cloning properly.
69//  if (SizeExpr)
70//    SizeExpr->Destroy(C);
71  this->~DependentSizedExtVectorType();
72  C.Deallocate(this);
73}
74
75/// getArrayElementTypeNoTypeQual - If this is an array type, return the
76/// element type of the array, potentially with type qualifiers missing.
77/// This method should never be used when type qualifiers are meaningful.
78const Type *Type::getArrayElementTypeNoTypeQual() const {
79  // If this is directly an array type, return it.
80  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
81    return ATy->getElementType().getTypePtr();
82
83  // If the canonical form of this type isn't the right kind, reject it.
84  if (!isa<ArrayType>(CanonicalType)) {
85    // Look through type qualifiers
86    if (ArrayType *AT = dyn_cast<ArrayType>(CanonicalType.getUnqualifiedType()))
87      return AT->getElementType().getTypePtr();
88    return 0;
89  }
90
91  // If this is a typedef for an array type, strip the typedef off without
92  // losing all typedef information.
93  return cast<ArrayType>(getDesugaredType())->getElementType().getTypePtr();
94}
95
96/// getDesugaredType - Return the specified type with any "sugar" removed from
97/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
98/// the type is already concrete, it returns it unmodified.  This is similar
99/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
100/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
101/// concrete.
102///
103/// \param ForDisplay When true, the desugaring is provided for
104/// display purposes only. In this case, we apply more heuristics to
105/// decide whether it is worth providing a desugared form of the type
106/// or not.
107QualType QualType::getDesugaredType(bool ForDisplay) const {
108  return getTypePtr()->getDesugaredType(ForDisplay)
109     .getWithAdditionalQualifiers(getCVRQualifiers());
110}
111
112/// getDesugaredType - Return the specified type with any "sugar" removed from
113/// type type.  This takes off typedefs, typeof's etc.  If the outer level of
114/// the type is already concrete, it returns it unmodified.  This is similar
115/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
116/// example, it return "T*" as "T*", (not as "int*"), because the pointer is
117/// concrete.
118///
119/// \param ForDisplay When true, the desugaring is provided for
120/// display purposes only. In this case, we apply more heuristics to
121/// decide whether it is worth providing a desugared form of the type
122/// or not.
123QualType Type::getDesugaredType(bool ForDisplay) const {
124  if (const TypedefType *TDT = dyn_cast<TypedefType>(this))
125    return TDT->LookThroughTypedefs().getDesugaredType();
126  if (const TypeOfExprType *TOE = dyn_cast<TypeOfExprType>(this))
127    return TOE->getUnderlyingExpr()->getType().getDesugaredType();
128  if (const TypeOfType *TOT = dyn_cast<TypeOfType>(this))
129    return TOT->getUnderlyingType().getDesugaredType();
130  if (const DecltypeType *DTT = dyn_cast<DecltypeType>(this)) {
131    if (!DTT->getUnderlyingType()->isDependentType())
132      return DTT->getUnderlyingType().getDesugaredType();
133  }
134  if (const TemplateSpecializationType *Spec
135        = dyn_cast<TemplateSpecializationType>(this)) {
136    if (ForDisplay)
137      return QualType(this, 0);
138
139    QualType Canon = Spec->getCanonicalTypeInternal();
140    if (Canon->getAsTemplateSpecializationType())
141      return QualType(this, 0);
142    return Canon->getDesugaredType();
143  }
144  if (const QualifiedNameType *QualName  = dyn_cast<QualifiedNameType>(this)) {
145    if (ForDisplay) {
146      // If desugaring the type that the qualified name is referring to
147      // produces something interesting, that's our desugared type.
148      QualType NamedType = QualName->getNamedType().getDesugaredType();
149      if (NamedType != QualName->getNamedType())
150        return NamedType;
151    } else
152      return QualName->getNamedType().getDesugaredType();
153  }
154
155  return QualType(this, 0);
156}
157
158/// isVoidType - Helper method to determine if this is the 'void' type.
159bool Type::isVoidType() const {
160  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
161    return BT->getKind() == BuiltinType::Void;
162  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
163    return AS->getBaseType()->isVoidType();
164  return false;
165}
166
167bool Type::isObjectType() const {
168  if (isa<FunctionType>(CanonicalType) || isa<ReferenceType>(CanonicalType) ||
169      isa<IncompleteArrayType>(CanonicalType) || isVoidType())
170    return false;
171  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
172    return AS->getBaseType()->isObjectType();
173  return true;
174}
175
176bool Type::isDerivedType() const {
177  switch (CanonicalType->getTypeClass()) {
178  case ExtQual:
179    return cast<ExtQualType>(CanonicalType)->getBaseType()->isDerivedType();
180  case Pointer:
181  case VariableArray:
182  case ConstantArray:
183  case ConstantArrayWithExpr:
184  case ConstantArrayWithoutExpr:
185  case IncompleteArray:
186  case FunctionProto:
187  case FunctionNoProto:
188  case LValueReference:
189  case RValueReference:
190  case Record:
191    return true;
192  default:
193    return false;
194  }
195}
196
197bool Type::isClassType() const {
198  if (const RecordType *RT = getAsRecordType())
199    return RT->getDecl()->isClass();
200  return false;
201}
202bool Type::isStructureType() const {
203  if (const RecordType *RT = getAsRecordType())
204    return RT->getDecl()->isStruct();
205  return false;
206}
207bool Type::isVoidPointerType() const {
208  if (const PointerType *PT = getAsPointerType())
209    return PT->getPointeeType()->isVoidType();
210  return false;
211}
212
213bool Type::isUnionType() const {
214  if (const RecordType *RT = getAsRecordType())
215    return RT->getDecl()->isUnion();
216  return false;
217}
218
219bool Type::isComplexType() const {
220  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
221    return CT->getElementType()->isFloatingType();
222  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
223    return AS->getBaseType()->isComplexType();
224  return false;
225}
226
227bool Type::isComplexIntegerType() const {
228  // Check for GCC complex integer extension.
229  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
230    return CT->getElementType()->isIntegerType();
231  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
232    return AS->getBaseType()->isComplexIntegerType();
233  return false;
234}
235
236const ComplexType *Type::getAsComplexIntegerType() const {
237  // Are we directly a complex type?
238  if (const ComplexType *CTy = dyn_cast<ComplexType>(this)) {
239    if (CTy->getElementType()->isIntegerType())
240      return CTy;
241    return 0;
242  }
243
244  // If the canonical form of this type isn't what we want, reject it.
245  if (!isa<ComplexType>(CanonicalType)) {
246    // Look through type qualifiers (e.g. ExtQualType's).
247    if (isa<ComplexType>(CanonicalType.getUnqualifiedType()))
248      return CanonicalType.getUnqualifiedType()->getAsComplexIntegerType();
249    return 0;
250  }
251
252  // If this is a typedef for a complex type, strip the typedef off without
253  // losing all typedef information.
254  return cast<ComplexType>(getDesugaredType());
255}
256
257const BuiltinType *Type::getAsBuiltinType() const {
258  // If this is directly a builtin type, return it.
259  if (const BuiltinType *BTy = dyn_cast<BuiltinType>(this))
260    return BTy;
261
262  // If the canonical form of this type isn't a builtin type, reject it.
263  if (!isa<BuiltinType>(CanonicalType)) {
264    // Look through type qualifiers (e.g. ExtQualType's).
265    if (isa<BuiltinType>(CanonicalType.getUnqualifiedType()))
266      return CanonicalType.getUnqualifiedType()->getAsBuiltinType();
267    return 0;
268  }
269
270  // If this is a typedef for a builtin type, strip the typedef off without
271  // losing all typedef information.
272  return cast<BuiltinType>(getDesugaredType());
273}
274
275const FunctionType *Type::getAsFunctionType() const {
276  // If this is directly a function type, return it.
277  if (const FunctionType *FTy = dyn_cast<FunctionType>(this))
278    return FTy;
279
280  // If the canonical form of this type isn't the right kind, reject it.
281  if (!isa<FunctionType>(CanonicalType)) {
282    // Look through type qualifiers
283    if (isa<FunctionType>(CanonicalType.getUnqualifiedType()))
284      return CanonicalType.getUnqualifiedType()->getAsFunctionType();
285    return 0;
286  }
287
288  // If this is a typedef for a function type, strip the typedef off without
289  // losing all typedef information.
290  return cast<FunctionType>(getDesugaredType());
291}
292
293const FunctionNoProtoType *Type::getAsFunctionNoProtoType() const {
294  return dyn_cast_or_null<FunctionNoProtoType>(getAsFunctionType());
295}
296
297const FunctionProtoType *Type::getAsFunctionProtoType() const {
298  return dyn_cast_or_null<FunctionProtoType>(getAsFunctionType());
299}
300
301QualType Type::getPointeeType() const {
302  if (const PointerType *PT = getAsPointerType())
303    return PT->getPointeeType();
304  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
305    return OPT->getPointeeType();
306  if (const BlockPointerType *BPT = getAsBlockPointerType())
307    return BPT->getPointeeType();
308  return QualType();
309}
310
311/// isVariablyModifiedType (C99 6.7.5p3) - Return true for variable length
312/// array types and types that contain variable array types in their
313/// declarator
314bool Type::isVariablyModifiedType() const {
315  // A VLA is a variably modified type.
316  if (isVariableArrayType())
317    return true;
318
319  // An array can contain a variably modified type
320  if (const Type *T = getArrayElementTypeNoTypeQual())
321    return T->isVariablyModifiedType();
322
323  // A pointer can point to a variably modified type.
324  // Also, C++ references and member pointers can point to a variably modified
325  // type, where VLAs appear as an extension to C++, and should be treated
326  // correctly.
327  if (const PointerType *PT = getAsPointerType())
328    return PT->getPointeeType()->isVariablyModifiedType();
329  if (const ReferenceType *RT = getAsReferenceType())
330    return RT->getPointeeType()->isVariablyModifiedType();
331  if (const MemberPointerType *PT = getAsMemberPointerType())
332    return PT->getPointeeType()->isVariablyModifiedType();
333
334  // A function can return a variably modified type
335  // This one isn't completely obvious, but it follows from the
336  // definition in C99 6.7.5p3. Because of this rule, it's
337  // illegal to declare a function returning a variably modified type.
338  if (const FunctionType *FT = getAsFunctionType())
339    return FT->getResultType()->isVariablyModifiedType();
340
341  return false;
342}
343
344const PointerType *Type::getAsPointerType() const {
345  return getAs<PointerType>();
346}
347const BlockPointerType *Type::getAsBlockPointerType() const {
348  return getAs<BlockPointerType>();
349}
350const ReferenceType *Type::getAsReferenceType() const {
351  return getAs<ReferenceType>();
352}
353const LValueReferenceType *Type::getAsLValueReferenceType() const {
354  return getAs<LValueReferenceType>();
355}
356const RValueReferenceType *Type::getAsRValueReferenceType() const {
357  return getAs<RValueReferenceType>();
358}
359const MemberPointerType *Type::getAsMemberPointerType() const {
360  return getAs<MemberPointerType>();
361}
362const TagType *Type::getAsTagType() const {
363  return getAs<TagType>();
364}
365const RecordType *Type::getAsRecordType() const {
366  return getAs<RecordType>();
367}
368const RecordType *Type::getAsStructureType() const {
369  // If this is directly a structure type, return it.
370  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
371    if (RT->getDecl()->isStruct())
372      return RT;
373  }
374
375  // If the canonical form of this type isn't the right kind, reject it.
376  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
377    if (!RT->getDecl()->isStruct())
378      return 0;
379
380    // If this is a typedef for a structure type, strip the typedef off without
381    // losing all typedef information.
382    return cast<RecordType>(getDesugaredType());
383  }
384  // Look through type qualifiers
385  if (isa<RecordType>(CanonicalType.getUnqualifiedType()))
386    return CanonicalType.getUnqualifiedType()->getAsStructureType();
387  return 0;
388}
389
390const RecordType *Type::getAsUnionType() const {
391  // If this is directly a union type, return it.
392  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
393    if (RT->getDecl()->isUnion())
394      return RT;
395  }
396
397  // If the canonical form of this type isn't the right kind, reject it.
398  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
399    if (!RT->getDecl()->isUnion())
400      return 0;
401
402    // If this is a typedef for a union type, strip the typedef off without
403    // losing all typedef information.
404    return cast<RecordType>(getDesugaredType());
405  }
406
407  // Look through type qualifiers
408  if (isa<RecordType>(CanonicalType.getUnqualifiedType()))
409    return CanonicalType.getUnqualifiedType()->getAsUnionType();
410  return 0;
411}
412
413const EnumType *Type::getAsEnumType() const {
414  // Check the canonicalized unqualified type directly; the more complex
415  // version is unnecessary because there isn't any typedef information
416  // to preserve.
417  return dyn_cast<EnumType>(CanonicalType.getUnqualifiedType());
418}
419
420const ComplexType *Type::getAsComplexType() const {
421  // Are we directly a complex type?
422  if (const ComplexType *CTy = dyn_cast<ComplexType>(this))
423    return CTy;
424
425  // If the canonical form of this type isn't the right kind, reject it.
426  if (!isa<ComplexType>(CanonicalType)) {
427    // Look through type qualifiers
428    if (isa<ComplexType>(CanonicalType.getUnqualifiedType()))
429      return CanonicalType.getUnqualifiedType()->getAsComplexType();
430    return 0;
431  }
432
433  // If this is a typedef for a complex type, strip the typedef off without
434  // losing all typedef information.
435  return cast<ComplexType>(getDesugaredType());
436}
437
438const VectorType *Type::getAsVectorType() const {
439  // Are we directly a vector type?
440  if (const VectorType *VTy = dyn_cast<VectorType>(this))
441    return VTy;
442
443  // If the canonical form of this type isn't the right kind, reject it.
444  if (!isa<VectorType>(CanonicalType)) {
445    // Look through type qualifiers
446    if (isa<VectorType>(CanonicalType.getUnqualifiedType()))
447      return CanonicalType.getUnqualifiedType()->getAsVectorType();
448    return 0;
449  }
450
451  // If this is a typedef for a vector type, strip the typedef off without
452  // losing all typedef information.
453  return cast<VectorType>(getDesugaredType());
454}
455
456const ExtVectorType *Type::getAsExtVectorType() const {
457  // Are we directly an OpenCU vector type?
458  if (const ExtVectorType *VTy = dyn_cast<ExtVectorType>(this))
459    return VTy;
460
461  // If the canonical form of this type isn't the right kind, reject it.
462  if (!isa<ExtVectorType>(CanonicalType)) {
463    // Look through type qualifiers
464    if (isa<ExtVectorType>(CanonicalType.getUnqualifiedType()))
465      return CanonicalType.getUnqualifiedType()->getAsExtVectorType();
466    return 0;
467  }
468
469  // If this is a typedef for an extended vector type, strip the typedef off
470  // without losing all typedef information.
471  return cast<ExtVectorType>(getDesugaredType());
472}
473
474const ObjCInterfaceType *Type::getAsObjCInterfaceType() const {
475  // There is no sugar for ObjCInterfaceType's, just return the canonical
476  // type pointer if it is the right class.  There is no typedef information to
477  // return and these cannot be Address-space qualified.
478  return dyn_cast<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
479}
480
481const ObjCInterfaceType *Type::getAsObjCQualifiedInterfaceType() const {
482  // There is no sugar for ObjCInterfaceType's, just return the canonical
483  // type pointer if it is the right class.  There is no typedef information to
484  // return and these cannot be Address-space qualified.
485  if (const ObjCInterfaceType *OIT = getAsObjCInterfaceType())
486    if (OIT->getNumProtocols())
487      return OIT;
488  return 0;
489}
490
491bool Type::isObjCQualifiedInterfaceType() const {
492  return getAsObjCQualifiedInterfaceType() != 0;
493}
494
495const ObjCObjectPointerType *Type::getAsObjCObjectPointerType() const {
496  // There is no sugar for ObjCObjectPointerType's, just return the
497  // canonical type pointer if it is the right class.
498  return dyn_cast<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
499}
500
501const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
502  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
503  // type pointer if it is the right class.
504  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType()) {
505    if (OPT->isObjCQualifiedIdType())
506      return OPT;
507  }
508  return 0;
509}
510
511const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
512  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType()) {
513    if (OPT->getInterfaceType())
514      return OPT;
515  }
516  return 0;
517}
518
519const TemplateTypeParmType *Type::getAsTemplateTypeParmType() const {
520  // There is no sugar for template type parameters, so just return
521  // the canonical type pointer if it is the right class.
522  // FIXME: can these be address-space qualified?
523  return dyn_cast<TemplateTypeParmType>(CanonicalType);
524}
525
526const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
527  if (const PointerType *PT = getAsPointerType())
528    if (const RecordType *RT = PT->getPointeeType()->getAsRecordType())
529      return dyn_cast<CXXRecordDecl>(RT->getDecl());
530  return 0;
531}
532
533const TemplateSpecializationType *
534Type::getAsTemplateSpecializationType() const {
535  // There is no sugar for class template specialization types, so
536  // just return the canonical type pointer if it is the right class.
537  return dyn_cast<TemplateSpecializationType>(CanonicalType);
538}
539
540bool Type::isIntegerType() const {
541  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
542    return BT->getKind() >= BuiltinType::Bool &&
543           BT->getKind() <= BuiltinType::Int128;
544  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
545    // Incomplete enum types are not treated as integer types.
546    // FIXME: In C++, enum types are never integer types.
547    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
548      return true;
549  if (isa<FixedWidthIntType>(CanonicalType))
550    return true;
551  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
552    return VT->getElementType()->isIntegerType();
553  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
554    return EXTQT->getBaseType()->isIntegerType();
555  return false;
556}
557
558bool Type::isIntegralType() const {
559  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
560    return BT->getKind() >= BuiltinType::Bool &&
561    BT->getKind() <= BuiltinType::LongLong;
562  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
563    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
564      return true;  // Complete enum types are integral.
565                    // FIXME: In C++, enum types are never integral.
566  if (isa<FixedWidthIntType>(CanonicalType))
567    return true;
568  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
569    return EXTQT->getBaseType()->isIntegralType();
570  return false;
571}
572
573bool Type::isEnumeralType() const {
574  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
575    return TT->getDecl()->isEnum();
576  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
577    return EXTQT->getBaseType()->isEnumeralType();
578  return false;
579}
580
581bool Type::isBooleanType() const {
582  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
583    return BT->getKind() == BuiltinType::Bool;
584  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
585    return EXTQT->getBaseType()->isBooleanType();
586  return false;
587}
588
589bool Type::isCharType() const {
590  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
591    return BT->getKind() == BuiltinType::Char_U ||
592           BT->getKind() == BuiltinType::UChar ||
593           BT->getKind() == BuiltinType::Char_S ||
594           BT->getKind() == BuiltinType::SChar;
595  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
596    return EXTQT->getBaseType()->isCharType();
597  return false;
598}
599
600bool Type::isWideCharType() const {
601  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
602    return BT->getKind() == BuiltinType::WChar;
603  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
604    return EXTQT->getBaseType()->isWideCharType();
605  return false;
606}
607
608/// isSignedIntegerType - Return true if this is an integer type that is
609/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
610/// an enum decl which has a signed representation, or a vector of signed
611/// integer element type.
612bool Type::isSignedIntegerType() const {
613  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
614    return BT->getKind() >= BuiltinType::Char_S &&
615           BT->getKind() <= BuiltinType::LongLong;
616  }
617
618  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
619    return ET->getDecl()->getIntegerType()->isSignedIntegerType();
620
621  if (const FixedWidthIntType *FWIT =
622          dyn_cast<FixedWidthIntType>(CanonicalType))
623    return FWIT->isSigned();
624
625  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
626    return VT->getElementType()->isSignedIntegerType();
627  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
628    return EXTQT->getBaseType()->isSignedIntegerType();
629  return false;
630}
631
632/// isUnsignedIntegerType - Return true if this is an integer type that is
633/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
634/// decl which has an unsigned representation, or a vector of unsigned integer
635/// element type.
636bool Type::isUnsignedIntegerType() const {
637  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
638    return BT->getKind() >= BuiltinType::Bool &&
639           BT->getKind() <= BuiltinType::ULongLong;
640  }
641
642  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
643    return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
644
645  if (const FixedWidthIntType *FWIT =
646          dyn_cast<FixedWidthIntType>(CanonicalType))
647    return !FWIT->isSigned();
648
649  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
650    return VT->getElementType()->isUnsignedIntegerType();
651  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
652    return EXTQT->getBaseType()->isUnsignedIntegerType();
653  return false;
654}
655
656bool Type::isFloatingType() const {
657  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
658    return BT->getKind() >= BuiltinType::Float &&
659           BT->getKind() <= BuiltinType::LongDouble;
660  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
661    return CT->getElementType()->isFloatingType();
662  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
663    return VT->getElementType()->isFloatingType();
664  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
665    return EXTQT->getBaseType()->isFloatingType();
666  return false;
667}
668
669bool Type::isRealFloatingType() const {
670  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
671    return BT->getKind() >= BuiltinType::Float &&
672           BT->getKind() <= BuiltinType::LongDouble;
673  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
674    return VT->getElementType()->isRealFloatingType();
675  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
676    return EXTQT->getBaseType()->isRealFloatingType();
677  return false;
678}
679
680bool Type::isRealType() const {
681  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
682    return BT->getKind() >= BuiltinType::Bool &&
683           BT->getKind() <= BuiltinType::LongDouble;
684  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
685    return TT->getDecl()->isEnum() && TT->getDecl()->isDefinition();
686  if (isa<FixedWidthIntType>(CanonicalType))
687    return true;
688  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
689    return VT->getElementType()->isRealType();
690  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
691    return EXTQT->getBaseType()->isRealType();
692  return false;
693}
694
695bool Type::isArithmeticType() const {
696  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
697    return BT->getKind() >= BuiltinType::Bool &&
698           BT->getKind() <= BuiltinType::LongDouble;
699  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
700    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
701    // If a body isn't seen by the time we get here, return false.
702    return ET->getDecl()->isDefinition();
703  if (isa<FixedWidthIntType>(CanonicalType))
704    return true;
705  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
706    return EXTQT->getBaseType()->isArithmeticType();
707  return isa<ComplexType>(CanonicalType) || isa<VectorType>(CanonicalType);
708}
709
710bool Type::isScalarType() const {
711  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
712    return BT->getKind() != BuiltinType::Void;
713  if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) {
714    // Enums are scalar types, but only if they are defined.  Incomplete enums
715    // are not treated as scalar types.
716    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
717      return true;
718    return false;
719  }
720  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
721    return EXTQT->getBaseType()->isScalarType();
722  if (isa<FixedWidthIntType>(CanonicalType))
723    return true;
724  return isa<PointerType>(CanonicalType) ||
725         isa<BlockPointerType>(CanonicalType) ||
726         isa<MemberPointerType>(CanonicalType) ||
727         isa<ComplexType>(CanonicalType) ||
728         isa<ObjCObjectPointerType>(CanonicalType);
729}
730
731/// \brief Determines whether the type is a C++ aggregate type or C
732/// aggregate or union type.
733///
734/// An aggregate type is an array or a class type (struct, union, or
735/// class) that has no user-declared constructors, no private or
736/// protected non-static data members, no base classes, and no virtual
737/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
738/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
739/// includes union types.
740bool Type::isAggregateType() const {
741  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
742    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
743      return ClassDecl->isAggregate();
744
745    return true;
746  }
747
748  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
749    return EXTQT->getBaseType()->isAggregateType();
750  return isa<ArrayType>(CanonicalType);
751}
752
753/// isConstantSizeType - Return true if this is not a variable sized type,
754/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
755/// incomplete types or dependent types.
756bool Type::isConstantSizeType() const {
757  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
758    return EXTQT->getBaseType()->isConstantSizeType();
759  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
760  assert(!isDependentType() && "This doesn't make sense for dependent types");
761  // The VAT must have a size, as it is known to be complete.
762  return !isa<VariableArrayType>(CanonicalType);
763}
764
765/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
766/// - a type that can describe objects, but which lacks information needed to
767/// determine its size.
768bool Type::isIncompleteType() const {
769  switch (CanonicalType->getTypeClass()) {
770  default: return false;
771  case ExtQual:
772    return cast<ExtQualType>(CanonicalType)->getBaseType()->isIncompleteType();
773  case Builtin:
774    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
775    // be completed.
776    return isVoidType();
777  case Record:
778  case Enum:
779    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
780    // forward declaration, but not a full definition (C99 6.2.5p22).
781    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
782  case IncompleteArray:
783    // An array of unknown size is an incomplete type (C99 6.2.5p22).
784    return true;
785  case ObjCInterface:
786    // ObjC interfaces are incomplete if they are @class, not @interface.
787    return cast<ObjCInterfaceType>(this)->getDecl()->isForwardDecl();
788  }
789}
790
791/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
792bool Type::isPODType() const {
793  // The compiler shouldn't query this for incomplete types, but the user might.
794  // We return false for that case.
795  if (isIncompleteType())
796    return false;
797
798  switch (CanonicalType->getTypeClass()) {
799    // Everything not explicitly mentioned is not POD.
800  default: return false;
801  case ExtQual:
802    return cast<ExtQualType>(CanonicalType)->getBaseType()->isPODType();
803  case VariableArray:
804  case ConstantArray:
805    // IncompleteArray is caught by isIncompleteType() above.
806    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
807
808  case Builtin:
809  case Complex:
810  case Pointer:
811  case MemberPointer:
812  case Vector:
813  case ExtVector:
814  case ObjCObjectPointer:
815    return true;
816
817  case Enum:
818    return true;
819
820  case Record:
821    if (CXXRecordDecl *ClassDecl
822          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
823      return ClassDecl->isPOD();
824
825    // C struct/union is POD.
826    return true;
827  }
828}
829
830bool Type::isPromotableIntegerType() const {
831  if (const BuiltinType *BT = getAsBuiltinType())
832    switch (BT->getKind()) {
833    case BuiltinType::Bool:
834    case BuiltinType::Char_S:
835    case BuiltinType::Char_U:
836    case BuiltinType::SChar:
837    case BuiltinType::UChar:
838    case BuiltinType::Short:
839    case BuiltinType::UShort:
840      return true;
841    default:
842      return false;
843    }
844  return false;
845}
846
847bool Type::isNullPtrType() const {
848  if (const BuiltinType *BT = getAsBuiltinType())
849    return BT->getKind() == BuiltinType::NullPtr;
850  return false;
851}
852
853bool Type::isSpecifierType() const {
854  // Note that this intentionally does not use the canonical type.
855  switch (getTypeClass()) {
856  case Builtin:
857  case Record:
858  case Enum:
859  case Typedef:
860  case Complex:
861  case TypeOfExpr:
862  case TypeOf:
863  case TemplateTypeParm:
864  case TemplateSpecialization:
865  case QualifiedName:
866  case Typename:
867  case ObjCInterface:
868  case ObjCObjectPointer:
869    return true;
870  default:
871    return false;
872  }
873}
874
875const char *BuiltinType::getName(const LangOptions &LO) const {
876  switch (getKind()) {
877  default: assert(0 && "Unknown builtin type!");
878  case Void:              return "void";
879  case Bool:              return LO.Bool ? "bool" : "_Bool";
880  case Char_S:            return "char";
881  case Char_U:            return "char";
882  case SChar:             return "signed char";
883  case Short:             return "short";
884  case Int:               return "int";
885  case Long:              return "long";
886  case LongLong:          return "long long";
887  case Int128:            return "__int128_t";
888  case UChar:             return "unsigned char";
889  case UShort:            return "unsigned short";
890  case UInt:              return "unsigned int";
891  case ULong:             return "unsigned long";
892  case ULongLong:         return "unsigned long long";
893  case UInt128:           return "__uint128_t";
894  case Float:             return "float";
895  case Double:            return "double";
896  case LongDouble:        return "long double";
897  case WChar:             return "wchar_t";
898  case Char16:            return "char16_t";
899  case Char32:            return "char32_t";
900  case NullPtr:           return "nullptr_t";
901  case Overload:          return "<overloaded function type>";
902  case Dependent:         return "<dependent type>";
903  case UndeducedAuto:     return "auto";
904  case ObjCId:            return "id";
905  case ObjCClass:         return "Class";
906  }
907}
908
909void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
910                                arg_type_iterator ArgTys,
911                                unsigned NumArgs, bool isVariadic,
912                                unsigned TypeQuals, bool hasExceptionSpec,
913                                bool anyExceptionSpec, unsigned NumExceptions,
914                                exception_iterator Exs, bool NoReturn) {
915  ID.AddPointer(Result.getAsOpaquePtr());
916  for (unsigned i = 0; i != NumArgs; ++i)
917    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
918  ID.AddInteger(isVariadic);
919  ID.AddInteger(TypeQuals);
920  ID.AddInteger(hasExceptionSpec);
921  if (hasExceptionSpec) {
922    ID.AddInteger(anyExceptionSpec);
923    for(unsigned i = 0; i != NumExceptions; ++i)
924      ID.AddPointer(Exs[i].getAsOpaquePtr());
925  }
926  ID.AddInteger(NoReturn);
927}
928
929void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
930  Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
931          getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
932          getNumExceptions(), exception_begin(), getNoReturnAttr());
933}
934
935void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID,
936                                    QualType OIT, ObjCProtocolDecl **protocols,
937                                    unsigned NumProtocols) {
938  ID.AddPointer(OIT.getAsOpaquePtr());
939  for (unsigned i = 0; i != NumProtocols; i++)
940    ID.AddPointer(protocols[i]);
941}
942
943void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID) {
944  if (getNumProtocols())
945    Profile(ID, getPointeeType(), &Protocols[0], getNumProtocols());
946  else
947    Profile(ID, getPointeeType(), 0, 0);
948}
949
950/// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
951/// potentially looking through *all* consequtive typedefs.  This returns the
952/// sum of the type qualifiers, so if you have:
953///   typedef const int A;
954///   typedef volatile A B;
955/// looking through the typedefs for B will give you "const volatile A".
956///
957QualType TypedefType::LookThroughTypedefs() const {
958  // Usually, there is only a single level of typedefs, be fast in that case.
959  QualType FirstType = getDecl()->getUnderlyingType();
960  if (!isa<TypedefType>(FirstType))
961    return FirstType;
962
963  // Otherwise, do the fully general loop.
964  unsigned TypeQuals = 0;
965  const TypedefType *TDT = this;
966  while (1) {
967    QualType CurType = TDT->getDecl()->getUnderlyingType();
968
969
970    /// FIXME:
971    /// FIXME: This is incorrect for ExtQuals!
972    /// FIXME:
973    TypeQuals |= CurType.getCVRQualifiers();
974
975    TDT = dyn_cast<TypedefType>(CurType);
976    if (TDT == 0)
977      return QualType(CurType.getTypePtr(), TypeQuals);
978  }
979}
980
981TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
982  : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) {
983}
984
985DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
986  : Type(Decltype, can, E->isTypeDependent()), E(E),
987  UnderlyingType(underlyingType) {
988}
989
990TagType::TagType(TypeClass TC, TagDecl *D, QualType can)
991  : Type(TC, can, D->isDependentType()), decl(D, 0) {}
992
993bool RecordType::classof(const TagType *TT) {
994  return isa<RecordDecl>(TT->getDecl());
995}
996
997bool EnumType::classof(const TagType *TT) {
998  return isa<EnumDecl>(TT->getDecl());
999}
1000
1001bool
1002TemplateSpecializationType::
1003anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) {
1004  for (unsigned Idx = 0; Idx < NumArgs; ++Idx) {
1005    switch (Args[Idx].getKind()) {
1006    case TemplateArgument::Null:
1007      assert(false && "Should not have a NULL template argument");
1008      break;
1009
1010    case TemplateArgument::Type:
1011      if (Args[Idx].getAsType()->isDependentType())
1012        return true;
1013      break;
1014
1015    case TemplateArgument::Declaration:
1016    case TemplateArgument::Integral:
1017      // Never dependent
1018      break;
1019
1020    case TemplateArgument::Expression:
1021      if (Args[Idx].getAsExpr()->isTypeDependent() ||
1022          Args[Idx].getAsExpr()->isValueDependent())
1023        return true;
1024      break;
1025
1026    case TemplateArgument::Pack:
1027      assert(0 && "FIXME: Implement!");
1028      break;
1029    }
1030  }
1031
1032  return false;
1033}
1034
1035TemplateSpecializationType::
1036TemplateSpecializationType(ASTContext &Context, TemplateName T,
1037                           const TemplateArgument *Args,
1038                           unsigned NumArgs, QualType Canon)
1039  : Type(TemplateSpecialization,
1040         Canon.isNull()? QualType(this, 0) : Canon,
1041         T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)),
1042    Context(Context),
1043    Template(T), NumArgs(NumArgs)
1044{
1045  assert((!Canon.isNull() ||
1046          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1047         "No canonical type for non-dependent class template specialization");
1048
1049  TemplateArgument *TemplateArgs
1050    = reinterpret_cast<TemplateArgument *>(this + 1);
1051  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
1052    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1053}
1054
1055void TemplateSpecializationType::Destroy(ASTContext& C) {
1056  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1057    // FIXME: Not all expressions get cloned, so we can't yet perform
1058    // this destruction.
1059    //    if (Expr *E = getArg(Arg).getAsExpr())
1060    //      E->Destroy(C);
1061  }
1062}
1063
1064TemplateSpecializationType::iterator
1065TemplateSpecializationType::end() const {
1066  return begin() + getNumArgs();
1067}
1068
1069const TemplateArgument &
1070TemplateSpecializationType::getArg(unsigned Idx) const {
1071  assert(Idx < getNumArgs() && "Template argument out of range");
1072  return getArgs()[Idx];
1073}
1074
1075void
1076TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1077                                    TemplateName T,
1078                                    const TemplateArgument *Args,
1079                                    unsigned NumArgs,
1080                                    ASTContext &Context) {
1081  T.Profile(ID);
1082  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1083    Args[Idx].Profile(ID, Context);
1084}
1085
1086const Type *QualifierSet::strip(const Type* T) {
1087  QualType DT = T->getDesugaredType();
1088  addCVR(DT.getCVRQualifiers());
1089
1090  if (const ExtQualType* EQT = dyn_cast<ExtQualType>(DT)) {
1091    if (EQT->getAddressSpace())
1092      addAddressSpace(EQT->getAddressSpace());
1093    if (EQT->getObjCGCAttr())
1094      addObjCGCAttrType(EQT->getObjCGCAttr());
1095    return EQT->getBaseType();
1096  } else {
1097    // Use the sugared type unless desugaring found extra qualifiers.
1098    return (DT.getCVRQualifiers() ? DT.getTypePtr() : T);
1099  }
1100}
1101
1102QualType QualifierSet::apply(QualType QT, ASTContext& C) {
1103  QT = QT.getWithAdditionalQualifiers(getCVRMask());
1104  if (hasObjCGCAttrType()) QT = C.getObjCGCQualType(QT, getObjCGCAttrType());
1105  if (hasAddressSpace()) QT = C.getAddrSpaceQualType(QT, getAddressSpace());
1106  return QT;
1107}
1108
1109
1110//===----------------------------------------------------------------------===//
1111// Type Printing
1112//===----------------------------------------------------------------------===//
1113
1114void QualType::dump(const char *msg) const {
1115  std::string R = "identifier";
1116  LangOptions LO;
1117  getAsStringInternal(R, PrintingPolicy(LO));
1118  if (msg)
1119    fprintf(stderr, "%s: %s\n", msg, R.c_str());
1120  else
1121    fprintf(stderr, "%s\n", R.c_str());
1122}
1123void QualType::dump() const {
1124  dump("");
1125}
1126
1127void Type::dump() const {
1128  std::string S = "identifier";
1129  LangOptions LO;
1130  getAsStringInternal(S, PrintingPolicy(LO));
1131  fprintf(stderr, "%s\n", S.c_str());
1132}
1133
1134
1135
1136static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
1137  // Note: funkiness to ensure we get a space only between quals.
1138  bool NonePrinted = true;
1139  if (TypeQuals & QualType::Const)
1140    S += "const", NonePrinted = false;
1141  if (TypeQuals & QualType::Volatile)
1142    S += (NonePrinted+" volatile"), NonePrinted = false;
1143  if (TypeQuals & QualType::Restrict)
1144    S += (NonePrinted+" restrict"), NonePrinted = false;
1145}
1146
1147std::string QualType::getAsString() const {
1148  std::string S;
1149  LangOptions LO;
1150  getAsStringInternal(S, PrintingPolicy(LO));
1151  return S;
1152}
1153
1154void
1155QualType::getAsStringInternal(std::string &S,
1156                              const PrintingPolicy &Policy) const {
1157  if (isNull()) {
1158    S += "NULL TYPE";
1159    return;
1160  }
1161
1162  if (Policy.SuppressSpecifiers && getTypePtr()->isSpecifierType())
1163    return;
1164
1165  // Print qualifiers as appropriate.
1166  if (unsigned Tq = getCVRQualifiers()) {
1167    std::string TQS;
1168    AppendTypeQualList(TQS, Tq);
1169    if (!S.empty())
1170      S = TQS + ' ' + S;
1171    else
1172      S = TQS;
1173  }
1174
1175  getTypePtr()->getAsStringInternal(S, Policy);
1176}
1177
1178void BuiltinType::getAsStringInternal(std::string &S,
1179                                      const PrintingPolicy &Policy) const {
1180  if (S.empty()) {
1181    S = getName(Policy.LangOpts);
1182  } else {
1183    // Prefix the basic type, e.g. 'int X'.
1184    S = ' ' + S;
1185    S = getName(Policy.LangOpts) + S;
1186  }
1187}
1188
1189void FixedWidthIntType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1190  // FIXME: Once we get bitwidth attribute, write as
1191  // "int __attribute__((bitwidth(x)))".
1192  std::string prefix = "__clang_fixedwidth";
1193  prefix += llvm::utostr_32(Width);
1194  prefix += (char)(Signed ? 'S' : 'U');
1195  if (S.empty()) {
1196    S = prefix;
1197  } else {
1198    // Prefix the basic type, e.g. 'int X'.
1199    S = prefix + S;
1200  }
1201}
1202
1203
1204void ComplexType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1205  ElementType->getAsStringInternal(S, Policy);
1206  S = "_Complex " + S;
1207}
1208
1209void ExtQualType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1210  bool NeedsSpace = false;
1211  if (AddressSpace) {
1212    S = "__attribute__((address_space("+llvm::utostr_32(AddressSpace)+")))" + S;
1213    NeedsSpace = true;
1214  }
1215  if (GCAttrType != QualType::GCNone) {
1216    if (NeedsSpace)
1217      S += ' ';
1218    S += "__attribute__((objc_gc(";
1219    if (GCAttrType == QualType::Weak)
1220      S += "weak";
1221    else
1222      S += "strong";
1223    S += ")))";
1224  }
1225  BaseType->getAsStringInternal(S, Policy);
1226}
1227
1228void PointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1229  S = '*' + S;
1230
1231  // Handle things like 'int (*A)[4];' correctly.
1232  // FIXME: this should include vectors, but vectors use attributes I guess.
1233  if (isa<ArrayType>(getPointeeType()))
1234    S = '(' + S + ')';
1235
1236  getPointeeType().getAsStringInternal(S, Policy);
1237}
1238
1239void BlockPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1240  S = '^' + S;
1241  PointeeType.getAsStringInternal(S, Policy);
1242}
1243
1244void LValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1245  S = '&' + S;
1246
1247  // Handle things like 'int (&A)[4];' correctly.
1248  // FIXME: this should include vectors, but vectors use attributes I guess.
1249  if (isa<ArrayType>(getPointeeType()))
1250    S = '(' + S + ')';
1251
1252  getPointeeType().getAsStringInternal(S, Policy);
1253}
1254
1255void RValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1256  S = "&&" + S;
1257
1258  // Handle things like 'int (&&A)[4];' correctly.
1259  // FIXME: this should include vectors, but vectors use attributes I guess.
1260  if (isa<ArrayType>(getPointeeType()))
1261    S = '(' + S + ')';
1262
1263  getPointeeType().getAsStringInternal(S, Policy);
1264}
1265
1266void MemberPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1267  std::string C;
1268  Class->getAsStringInternal(C, Policy);
1269  C += "::*";
1270  S = C + S;
1271
1272  // Handle things like 'int (Cls::*A)[4];' correctly.
1273  // FIXME: this should include vectors, but vectors use attributes I guess.
1274  if (isa<ArrayType>(getPointeeType()))
1275    S = '(' + S + ')';
1276
1277  getPointeeType().getAsStringInternal(S, Policy);
1278}
1279
1280void ConstantArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1281  S += '[';
1282  S += llvm::utostr(getSize().getZExtValue());
1283  S += ']';
1284
1285  getElementType().getAsStringInternal(S, Policy);
1286}
1287
1288void ConstantArrayWithExprType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1289  if (Policy.ConstantArraySizeAsWritten) {
1290    std::string SStr;
1291    llvm::raw_string_ostream s(SStr);
1292    getSizeExpr()->printPretty(s, 0, Policy);
1293    S += '[';
1294    S += s.str();
1295    S += ']';
1296    getElementType().getAsStringInternal(S, Policy);
1297  }
1298  else
1299    ConstantArrayType::getAsStringInternal(S, Policy);
1300}
1301
1302void ConstantArrayWithoutExprType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1303  if (Policy.ConstantArraySizeAsWritten) {
1304    S += "[]";
1305    getElementType().getAsStringInternal(S, Policy);
1306  }
1307  else
1308    ConstantArrayType::getAsStringInternal(S, Policy);
1309}
1310
1311void IncompleteArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1312  S += "[]";
1313
1314  getElementType().getAsStringInternal(S, Policy);
1315}
1316
1317void VariableArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1318  S += '[';
1319
1320  if (getIndexTypeQualifier()) {
1321    AppendTypeQualList(S, getIndexTypeQualifier());
1322    S += ' ';
1323  }
1324
1325  if (getSizeModifier() == Static)
1326    S += "static";
1327  else if (getSizeModifier() == Star)
1328    S += '*';
1329
1330  if (getSizeExpr()) {
1331    std::string SStr;
1332    llvm::raw_string_ostream s(SStr);
1333    getSizeExpr()->printPretty(s, 0, Policy);
1334    S += s.str();
1335  }
1336  S += ']';
1337
1338  getElementType().getAsStringInternal(S, Policy);
1339}
1340
1341void DependentSizedArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1342  S += '[';
1343
1344  if (getIndexTypeQualifier()) {
1345    AppendTypeQualList(S, getIndexTypeQualifier());
1346    S += ' ';
1347  }
1348
1349  if (getSizeModifier() == Static)
1350    S += "static";
1351  else if (getSizeModifier() == Star)
1352    S += '*';
1353
1354  if (getSizeExpr()) {
1355    std::string SStr;
1356    llvm::raw_string_ostream s(SStr);
1357    getSizeExpr()->printPretty(s, 0, Policy);
1358    S += s.str();
1359  }
1360  S += ']';
1361
1362  getElementType().getAsStringInternal(S, Policy);
1363}
1364
1365void DependentSizedExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1366  getElementType().getAsStringInternal(S, Policy);
1367
1368  S += " __attribute__((ext_vector_type(";
1369  if (getSizeExpr()) {
1370    std::string SStr;
1371    llvm::raw_string_ostream s(SStr);
1372    getSizeExpr()->printPretty(s, 0, Policy);
1373    S += s.str();
1374  }
1375  S += ")))";
1376}
1377
1378void VectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1379  // FIXME: We prefer to print the size directly here, but have no way
1380  // to get the size of the type.
1381  S += " __attribute__((__vector_size__(";
1382  S += llvm::utostr_32(NumElements); // convert back to bytes.
1383  S += " * sizeof(" + ElementType.getAsString() + "))))";
1384  ElementType.getAsStringInternal(S, Policy);
1385}
1386
1387void ExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1388  S += " __attribute__((ext_vector_type(";
1389  S += llvm::utostr_32(NumElements);
1390  S += ")))";
1391  ElementType.getAsStringInternal(S, Policy);
1392}
1393
1394void TypeOfExprType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1395  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
1396    InnerString = ' ' + InnerString;
1397  std::string Str;
1398  llvm::raw_string_ostream s(Str);
1399  getUnderlyingExpr()->printPretty(s, 0, Policy);
1400  InnerString = "typeof " + s.str() + InnerString;
1401}
1402
1403void TypeOfType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1404  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
1405    InnerString = ' ' + InnerString;
1406  std::string Tmp;
1407  getUnderlyingType().getAsStringInternal(Tmp, Policy);
1408  InnerString = "typeof(" + Tmp + ")" + InnerString;
1409}
1410
1411void DecltypeType::getAsStringInternal(std::string &InnerString,
1412                                       const PrintingPolicy &Policy) const {
1413  if (!InnerString.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
1414    InnerString = ' ' + InnerString;
1415  std::string Str;
1416  llvm::raw_string_ostream s(Str);
1417  getUnderlyingExpr()->printPretty(s, 0, Policy);
1418  InnerString = "decltype(" + s.str() + ")" + InnerString;
1419}
1420
1421void FunctionNoProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1422  // If needed for precedence reasons, wrap the inner part in grouping parens.
1423  if (!S.empty())
1424    S = "(" + S + ")";
1425
1426  S += "()";
1427  if (getNoReturnAttr())
1428    S += " __attribute__((noreturn))";
1429  getResultType().getAsStringInternal(S, Policy);
1430}
1431
1432void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1433  // If needed for precedence reasons, wrap the inner part in grouping parens.
1434  if (!S.empty())
1435    S = "(" + S + ")";
1436
1437  S += "(";
1438  std::string Tmp;
1439  PrintingPolicy ParamPolicy(Policy);
1440  ParamPolicy.SuppressSpecifiers = false;
1441  for (unsigned i = 0, e = getNumArgs(); i != e; ++i) {
1442    if (i) S += ", ";
1443    getArgType(i).getAsStringInternal(Tmp, ParamPolicy);
1444    S += Tmp;
1445    Tmp.clear();
1446  }
1447
1448  if (isVariadic()) {
1449    if (getNumArgs())
1450      S += ", ";
1451    S += "...";
1452  } else if (getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
1453    // Do not emit int() if we have a proto, emit 'int(void)'.
1454    S += "void";
1455  }
1456
1457  S += ")";
1458  if (getNoReturnAttr())
1459    S += " __attribute__((noreturn))";
1460  getResultType().getAsStringInternal(S, Policy);
1461}
1462
1463
1464void TypedefType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1465  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1466    InnerString = ' ' + InnerString;
1467  InnerString = getDecl()->getIdentifier()->getName() + InnerString;
1468}
1469
1470void TemplateTypeParmType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1471  if (!InnerString.empty())    // Prefix the basic type, e.g. 'parmname X'.
1472    InnerString = ' ' + InnerString;
1473
1474  if (!Name)
1475    InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' +
1476      llvm::utostr_32(Index) + InnerString;
1477  else
1478    InnerString = Name->getName() + InnerString;
1479}
1480
1481std::string
1482TemplateSpecializationType::PrintTemplateArgumentList(
1483                                                  const TemplateArgument *Args,
1484                                                  unsigned NumArgs,
1485                                                  const PrintingPolicy &Policy) {
1486  std::string SpecString;
1487  SpecString += '<';
1488  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1489    if (Arg)
1490      SpecString += ", ";
1491
1492    // Print the argument into a string.
1493    std::string ArgString;
1494    switch (Args[Arg].getKind()) {
1495    case TemplateArgument::Null:
1496      assert(false && "Null template argument");
1497      break;
1498
1499    case TemplateArgument::Type:
1500      Args[Arg].getAsType().getAsStringInternal(ArgString, Policy);
1501      break;
1502
1503    case TemplateArgument::Declaration:
1504      ArgString = cast<NamedDecl>(Args[Arg].getAsDecl())->getNameAsString();
1505      break;
1506
1507    case TemplateArgument::Integral:
1508      ArgString = Args[Arg].getAsIntegral()->toString(10, true);
1509      break;
1510
1511    case TemplateArgument::Expression: {
1512      llvm::raw_string_ostream s(ArgString);
1513      Args[Arg].getAsExpr()->printPretty(s, 0, Policy);
1514      break;
1515    }
1516    case TemplateArgument::Pack:
1517      assert(0 && "FIXME: Implement!");
1518      break;
1519    }
1520
1521    // If this is the first argument and its string representation
1522    // begins with the global scope specifier ('::foo'), add a space
1523    // to avoid printing the diagraph '<:'.
1524    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1525      SpecString += ' ';
1526
1527    SpecString += ArgString;
1528  }
1529
1530  // If the last character of our string is '>', add another space to
1531  // keep the two '>''s separate tokens. We don't *have* to do this in
1532  // C++0x, but it's still good hygiene.
1533  if (SpecString[SpecString.size() - 1] == '>')
1534    SpecString += ' ';
1535
1536  SpecString += '>';
1537
1538  return SpecString;
1539}
1540
1541void
1542TemplateSpecializationType::
1543getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1544  std::string SpecString;
1545
1546  {
1547    llvm::raw_string_ostream OS(SpecString);
1548    Template.print(OS, Policy);
1549  }
1550
1551  SpecString += PrintTemplateArgumentList(getArgs(), getNumArgs(), Policy);
1552  if (InnerString.empty())
1553    InnerString.swap(SpecString);
1554  else
1555    InnerString = SpecString + ' ' + InnerString;
1556}
1557
1558void QualifiedNameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1559  std::string MyString;
1560
1561  {
1562    llvm::raw_string_ostream OS(MyString);
1563    NNS->print(OS, Policy);
1564  }
1565
1566  std::string TypeStr;
1567  PrintingPolicy InnerPolicy(Policy);
1568  InnerPolicy.SuppressTagKind = true;
1569  NamedType.getAsStringInternal(TypeStr, InnerPolicy);
1570
1571  MyString += TypeStr;
1572  if (InnerString.empty())
1573    InnerString.swap(MyString);
1574  else
1575    InnerString = MyString + ' ' + InnerString;
1576}
1577
1578void TypenameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1579  std::string MyString;
1580
1581  {
1582    llvm::raw_string_ostream OS(MyString);
1583    OS << "typename ";
1584    NNS->print(OS, Policy);
1585
1586    if (const IdentifierInfo *Ident = getIdentifier())
1587      OS << Ident->getName();
1588    else if (const TemplateSpecializationType *Spec = getTemplateId()) {
1589      Spec->getTemplateName().print(OS, Policy, true);
1590      OS << TemplateSpecializationType::PrintTemplateArgumentList(
1591                                                               Spec->getArgs(),
1592                                                            Spec->getNumArgs(),
1593                                                               Policy);
1594    }
1595  }
1596
1597  if (InnerString.empty())
1598    InnerString.swap(MyString);
1599  else
1600    InnerString = MyString + ' ' + InnerString;
1601}
1602
1603void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID,
1604                                         const ObjCInterfaceDecl *Decl,
1605                                         ObjCProtocolDecl **protocols,
1606                                         unsigned NumProtocols) {
1607  ID.AddPointer(Decl);
1608  for (unsigned i = 0; i != NumProtocols; i++)
1609    ID.AddPointer(protocols[i]);
1610}
1611
1612void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID) {
1613  if (getNumProtocols())
1614    Profile(ID, getDecl(), &Protocols[0], getNumProtocols());
1615  else
1616    Profile(ID, getDecl(), 0, 0);
1617}
1618
1619void ObjCInterfaceType::getAsStringInternal(std::string &InnerString,
1620                                           const PrintingPolicy &Policy) const {
1621  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1622    InnerString = ' ' + InnerString;
1623
1624  std::string ObjCQIString = getDecl()->getNameAsString();
1625  if (getNumProtocols()) {
1626    ObjCQIString += '<';
1627    bool isFirst = true;
1628    for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1629      if (isFirst)
1630        isFirst = false;
1631      else
1632        ObjCQIString += ',';
1633      ObjCQIString += (*I)->getNameAsString();
1634    }
1635    ObjCQIString += '>';
1636  }
1637  InnerString = ObjCQIString + InnerString;
1638}
1639
1640void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString,
1641                                                const PrintingPolicy &Policy) const {
1642  std::string ObjCQIString;
1643
1644  if (isObjCIdType() || isObjCQualifiedIdType())
1645    ObjCQIString = "id";
1646  else if (isObjCClassType() || isObjCQualifiedClassType())
1647    ObjCQIString = "Class";
1648  else
1649    ObjCQIString = getInterfaceDecl()->getNameAsString();
1650
1651  if (!qual_empty()) {
1652    ObjCQIString += '<';
1653    for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1654      ObjCQIString += (*I)->getNameAsString();
1655      if (I+1 != E)
1656        ObjCQIString += ',';
1657    }
1658    ObjCQIString += '>';
1659  }
1660  if (!isObjCIdType() && !isObjCQualifiedIdType())
1661    ObjCQIString += " *"; // Don't forget the implicit pointer.
1662  else if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1663    InnerString = ' ' + InnerString;
1664
1665  InnerString = ObjCQIString + InnerString;
1666}
1667
1668void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1669  if (Policy.SuppressTag)
1670    return;
1671
1672  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1673    InnerString = ' ' + InnerString;
1674
1675  const char *Kind = Policy.SuppressTagKind? 0 : getDecl()->getKindName();
1676  const char *ID;
1677  if (const IdentifierInfo *II = getDecl()->getIdentifier())
1678    ID = II->getName();
1679  else if (TypedefDecl *Typedef = getDecl()->getTypedefForAnonDecl()) {
1680    Kind = 0;
1681    assert(Typedef->getIdentifier() && "Typedef without identifier?");
1682    ID = Typedef->getIdentifier()->getName();
1683  } else
1684    ID = "<anonymous>";
1685
1686  // If this is a class template specialization, print the template
1687  // arguments.
1688  if (ClassTemplateSpecializationDecl *Spec
1689        = dyn_cast<ClassTemplateSpecializationDecl>(getDecl())) {
1690    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1691    std::string TemplateArgsStr
1692      = TemplateSpecializationType::PrintTemplateArgumentList(
1693                                            TemplateArgs.getFlatArgumentList(),
1694                                            TemplateArgs.flat_size(),
1695                                                              Policy);
1696    InnerString = TemplateArgsStr + InnerString;
1697  }
1698
1699  if (Kind) {
1700    // Compute the full nested-name-specifier for this type. In C,
1701    // this will always be empty.
1702    std::string ContextStr;
1703    for (DeclContext *DC = getDecl()->getDeclContext();
1704         !DC->isTranslationUnit(); DC = DC->getParent()) {
1705      std::string MyPart;
1706      if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
1707        if (NS->getIdentifier())
1708          MyPart = NS->getNameAsString();
1709      } else if (ClassTemplateSpecializationDecl *Spec
1710                   = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1711        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1712        std::string TemplateArgsStr
1713          = TemplateSpecializationType::PrintTemplateArgumentList(
1714                                           TemplateArgs.getFlatArgumentList(),
1715                                           TemplateArgs.flat_size(),
1716                                           Policy);
1717        MyPart = Spec->getIdentifier()->getName() + TemplateArgsStr;
1718      } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
1719        if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
1720          MyPart = Typedef->getIdentifier()->getName();
1721        else if (Tag->getIdentifier())
1722          MyPart = Tag->getIdentifier()->getName();
1723      }
1724
1725      if (!MyPart.empty())
1726        ContextStr = MyPart + "::" + ContextStr;
1727    }
1728
1729    InnerString = std::string(Kind) + " " + ContextStr + ID + InnerString;
1730  } else
1731    InnerString = ID + InnerString;
1732}
1733