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