Type.cpp revision e4f2142d00fa5fdb580c4e2413da91882d955381
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(const LangOptions &LO) const {
942  switch (getKind()) {
943  default: assert(0 && "Unknown builtin type!");
944  case Void:              return "void";
945  case Bool:              return LO.Bool ? "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  case UndeducedAuto:     return "<undeduced auto type>";
968  }
969}
970
971void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
972                                arg_type_iterator ArgTys,
973                                unsigned NumArgs, bool isVariadic,
974                                unsigned TypeQuals, bool hasExceptionSpec,
975                                bool anyExceptionSpec, unsigned NumExceptions,
976                                exception_iterator Exs) {
977  ID.AddPointer(Result.getAsOpaquePtr());
978  for (unsigned i = 0; i != NumArgs; ++i)
979    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
980  ID.AddInteger(isVariadic);
981  ID.AddInteger(TypeQuals);
982  ID.AddInteger(hasExceptionSpec);
983  if (hasExceptionSpec) {
984    ID.AddInteger(anyExceptionSpec);
985    for(unsigned i = 0; i != NumExceptions; ++i)
986      ID.AddPointer(Exs[i].getAsOpaquePtr());
987  }
988}
989
990void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
991  Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
992          getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
993          getNumExceptions(), exception_begin());
994}
995
996void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID,
997                                    const ObjCInterfaceDecl *Decl,
998                                    ObjCProtocolDecl **protocols,
999                                    unsigned NumProtocols) {
1000  ID.AddPointer(Decl);
1001  for (unsigned i = 0; i != NumProtocols; i++)
1002    ID.AddPointer(protocols[i]);
1003}
1004
1005void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID) {
1006  Profile(ID, getDecl(), &Protocols[0], getNumProtocols());
1007}
1008
1009void ObjCQualifiedInterfaceType::Profile(llvm::FoldingSetNodeID &ID,
1010                                         const ObjCInterfaceDecl *Decl,
1011                                         ObjCProtocolDecl **protocols,
1012                                         unsigned NumProtocols) {
1013  ID.AddPointer(Decl);
1014  for (unsigned i = 0; i != NumProtocols; i++)
1015    ID.AddPointer(protocols[i]);
1016}
1017
1018void ObjCQualifiedInterfaceType::Profile(llvm::FoldingSetNodeID &ID) {
1019  Profile(ID, getDecl(), &Protocols[0], getNumProtocols());
1020}
1021
1022/// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1023/// potentially looking through *all* consequtive typedefs.  This returns the
1024/// sum of the type qualifiers, so if you have:
1025///   typedef const int A;
1026///   typedef volatile A B;
1027/// looking through the typedefs for B will give you "const volatile A".
1028///
1029QualType TypedefType::LookThroughTypedefs() const {
1030  // Usually, there is only a single level of typedefs, be fast in that case.
1031  QualType FirstType = getDecl()->getUnderlyingType();
1032  if (!isa<TypedefType>(FirstType))
1033    return FirstType;
1034
1035  // Otherwise, do the fully general loop.
1036  unsigned TypeQuals = 0;
1037  const TypedefType *TDT = this;
1038  while (1) {
1039    QualType CurType = TDT->getDecl()->getUnderlyingType();
1040
1041
1042    /// FIXME:
1043    /// FIXME: This is incorrect for ExtQuals!
1044    /// FIXME:
1045    TypeQuals |= CurType.getCVRQualifiers();
1046
1047    TDT = dyn_cast<TypedefType>(CurType);
1048    if (TDT == 0)
1049      return QualType(CurType.getTypePtr(), TypeQuals);
1050  }
1051}
1052
1053TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1054  : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) {
1055  assert(!isa<TypedefType>(can) && "Invalid canonical type");
1056}
1057
1058DecltypeType::DecltypeType(Expr *E, QualType can)
1059  : Type(Decltype, can, E->isTypeDependent()), E(E) {
1060  assert(can->isDependentType() == E->isTypeDependent() &&
1061         "type dependency mismatch!");
1062  assert(!isa<TypedefType>(can) && "Invalid canonical type");
1063}
1064
1065TagType::TagType(TypeClass TC, TagDecl *D, QualType can)
1066  : Type(TC, can, D->isDependentType()), decl(D, 0) {}
1067
1068bool RecordType::classof(const TagType *TT) {
1069  return isa<RecordDecl>(TT->getDecl());
1070}
1071
1072bool EnumType::classof(const TagType *TT) {
1073  return isa<EnumDecl>(TT->getDecl());
1074}
1075
1076bool
1077TemplateSpecializationType::
1078anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) {
1079  for (unsigned Idx = 0; Idx < NumArgs; ++Idx) {
1080    switch (Args[Idx].getKind()) {
1081    case TemplateArgument::Null:
1082      assert(false && "Should not have a NULL template argument");
1083      break;
1084
1085    case TemplateArgument::Type:
1086      if (Args[Idx].getAsType()->isDependentType())
1087        return true;
1088      break;
1089
1090    case TemplateArgument::Declaration:
1091    case TemplateArgument::Integral:
1092      // Never dependent
1093      break;
1094
1095    case TemplateArgument::Expression:
1096      if (Args[Idx].getAsExpr()->isTypeDependent() ||
1097          Args[Idx].getAsExpr()->isValueDependent())
1098        return true;
1099      break;
1100
1101    case TemplateArgument::Pack:
1102      assert(0 && "FIXME: Implement!");
1103      break;
1104    }
1105  }
1106
1107  return false;
1108}
1109
1110TemplateSpecializationType::
1111TemplateSpecializationType(TemplateName T, const TemplateArgument *Args,
1112                           unsigned NumArgs, QualType Canon)
1113  : Type(TemplateSpecialization,
1114         Canon.isNull()? QualType(this, 0) : Canon,
1115         T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)),
1116    Template(T), NumArgs(NumArgs)
1117{
1118  assert((!Canon.isNull() ||
1119          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1120         "No canonical type for non-dependent class template specialization");
1121
1122  TemplateArgument *TemplateArgs
1123    = reinterpret_cast<TemplateArgument *>(this + 1);
1124  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
1125    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1126}
1127
1128void TemplateSpecializationType::Destroy(ASTContext& C) {
1129  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1130    // FIXME: Not all expressions get cloned, so we can't yet perform
1131    // this destruction.
1132    //    if (Expr *E = getArg(Arg).getAsExpr())
1133    //      E->Destroy(C);
1134  }
1135}
1136
1137TemplateSpecializationType::iterator
1138TemplateSpecializationType::end() const {
1139  return begin() + getNumArgs();
1140}
1141
1142const TemplateArgument &
1143TemplateSpecializationType::getArg(unsigned Idx) const {
1144  assert(Idx < getNumArgs() && "Template argument out of range");
1145  return getArgs()[Idx];
1146}
1147
1148void
1149TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1150                                    TemplateName T,
1151                                    const TemplateArgument *Args,
1152                                    unsigned NumArgs) {
1153  T.Profile(ID);
1154  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1155    Args[Idx].Profile(ID);
1156}
1157
1158//===----------------------------------------------------------------------===//
1159// Type Printing
1160//===----------------------------------------------------------------------===//
1161
1162void QualType::dump(const char *msg) const {
1163  std::string R = "identifier";
1164  LangOptions LO;
1165  getAsStringInternal(R, PrintingPolicy(LO));
1166  if (msg)
1167    fprintf(stderr, "%s: %s\n", msg, R.c_str());
1168  else
1169    fprintf(stderr, "%s\n", R.c_str());
1170}
1171void QualType::dump() const {
1172  dump("");
1173}
1174
1175void Type::dump() const {
1176  std::string S = "identifier";
1177  LangOptions LO;
1178  getAsStringInternal(S, PrintingPolicy(LO));
1179  fprintf(stderr, "%s\n", S.c_str());
1180}
1181
1182
1183
1184static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
1185  // Note: funkiness to ensure we get a space only between quals.
1186  bool NonePrinted = true;
1187  if (TypeQuals & QualType::Const)
1188    S += "const", NonePrinted = false;
1189  if (TypeQuals & QualType::Volatile)
1190    S += (NonePrinted+" volatile"), NonePrinted = false;
1191  if (TypeQuals & QualType::Restrict)
1192    S += (NonePrinted+" restrict"), NonePrinted = false;
1193}
1194
1195std::string QualType::getAsString() const {
1196  std::string S;
1197  LangOptions LO;
1198  getAsStringInternal(S, PrintingPolicy(LO));
1199  return S;
1200}
1201
1202void
1203QualType::getAsStringInternal(std::string &S,
1204                              const PrintingPolicy &Policy) const {
1205  if (isNull()) {
1206    S += "NULL TYPE";
1207    return;
1208  }
1209
1210  if (Policy.SuppressSpecifiers && getTypePtr()->isSpecifierType())
1211    return;
1212
1213  // Print qualifiers as appropriate.
1214  if (unsigned Tq = getCVRQualifiers()) {
1215    std::string TQS;
1216    AppendTypeQualList(TQS, Tq);
1217    if (!S.empty())
1218      S = TQS + ' ' + S;
1219    else
1220      S = TQS;
1221  }
1222
1223  getTypePtr()->getAsStringInternal(S, Policy);
1224}
1225
1226void BuiltinType::getAsStringInternal(std::string &S,
1227                                      const PrintingPolicy &Policy) const {
1228  if (S.empty()) {
1229    S = getName(Policy.LangOpts);
1230  } else {
1231    // Prefix the basic type, e.g. 'int X'.
1232    S = ' ' + S;
1233    S = getName(Policy.LangOpts) + S;
1234  }
1235}
1236
1237void FixedWidthIntType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1238  // FIXME: Once we get bitwidth attribute, write as
1239  // "int __attribute__((bitwidth(x)))".
1240  std::string prefix = "__clang_fixedwidth";
1241  prefix += llvm::utostr_32(Width);
1242  prefix += (char)(Signed ? 'S' : 'U');
1243  if (S.empty()) {
1244    S = prefix;
1245  } else {
1246    // Prefix the basic type, e.g. 'int X'.
1247    S = prefix + S;
1248  }
1249}
1250
1251
1252void ComplexType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1253  ElementType->getAsStringInternal(S, Policy);
1254  S = "_Complex " + S;
1255}
1256
1257void ExtQualType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1258  bool NeedsSpace = false;
1259  if (AddressSpace) {
1260    S = "__attribute__((address_space("+llvm::utostr_32(AddressSpace)+")))" + S;
1261    NeedsSpace = true;
1262  }
1263  if (GCAttrType != QualType::GCNone) {
1264    if (NeedsSpace)
1265      S += ' ';
1266    S += "__attribute__((objc_gc(";
1267    if (GCAttrType == QualType::Weak)
1268      S += "weak";
1269    else
1270      S += "strong";
1271    S += ")))";
1272  }
1273  BaseType->getAsStringInternal(S, Policy);
1274}
1275
1276void PointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1277  S = '*' + S;
1278
1279  // Handle things like 'int (*A)[4];' correctly.
1280  // FIXME: this should include vectors, but vectors use attributes I guess.
1281  if (isa<ArrayType>(getPointeeType()))
1282    S = '(' + S + ')';
1283
1284  getPointeeType().getAsStringInternal(S, Policy);
1285}
1286
1287void BlockPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1288  S = '^' + S;
1289  PointeeType.getAsStringInternal(S, Policy);
1290}
1291
1292void LValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1293  S = '&' + S;
1294
1295  // Handle things like 'int (&A)[4];' correctly.
1296  // FIXME: this should include vectors, but vectors use attributes I guess.
1297  if (isa<ArrayType>(getPointeeType()))
1298    S = '(' + S + ')';
1299
1300  getPointeeType().getAsStringInternal(S, Policy);
1301}
1302
1303void RValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1304  S = "&&" + S;
1305
1306  // Handle things like 'int (&&A)[4];' correctly.
1307  // FIXME: this should include vectors, but vectors use attributes I guess.
1308  if (isa<ArrayType>(getPointeeType()))
1309    S = '(' + S + ')';
1310
1311  getPointeeType().getAsStringInternal(S, Policy);
1312}
1313
1314void MemberPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1315  std::string C;
1316  Class->getAsStringInternal(C, Policy);
1317  C += "::*";
1318  S = C + S;
1319
1320  // Handle things like 'int (Cls::*A)[4];' correctly.
1321  // FIXME: this should include vectors, but vectors use attributes I guess.
1322  if (isa<ArrayType>(getPointeeType()))
1323    S = '(' + S + ')';
1324
1325  getPointeeType().getAsStringInternal(S, Policy);
1326}
1327
1328void ConstantArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1329  S += '[';
1330  S += llvm::utostr(getSize().getZExtValue());
1331  S += ']';
1332
1333  getElementType().getAsStringInternal(S, Policy);
1334}
1335
1336void IncompleteArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1337  S += "[]";
1338
1339  getElementType().getAsStringInternal(S, Policy);
1340}
1341
1342void VariableArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1343  S += '[';
1344
1345  if (getIndexTypeQualifier()) {
1346    AppendTypeQualList(S, getIndexTypeQualifier());
1347    S += ' ';
1348  }
1349
1350  if (getSizeModifier() == Static)
1351    S += "static";
1352  else if (getSizeModifier() == Star)
1353    S += '*';
1354
1355  if (getSizeExpr()) {
1356    std::string SStr;
1357    llvm::raw_string_ostream s(SStr);
1358    getSizeExpr()->printPretty(s, 0, Policy);
1359    S += s.str();
1360  }
1361  S += ']';
1362
1363  getElementType().getAsStringInternal(S, Policy);
1364}
1365
1366void DependentSizedArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1367  S += '[';
1368
1369  if (getIndexTypeQualifier()) {
1370    AppendTypeQualList(S, getIndexTypeQualifier());
1371    S += ' ';
1372  }
1373
1374  if (getSizeModifier() == Static)
1375    S += "static";
1376  else if (getSizeModifier() == Star)
1377    S += '*';
1378
1379  if (getSizeExpr()) {
1380    std::string SStr;
1381    llvm::raw_string_ostream s(SStr);
1382    getSizeExpr()->printPretty(s, 0, Policy);
1383    S += s.str();
1384  }
1385  S += ']';
1386
1387  getElementType().getAsStringInternal(S, Policy);
1388}
1389
1390void DependentSizedExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1391  getElementType().getAsStringInternal(S, Policy);
1392
1393  S += " __attribute__((ext_vector_type(";
1394  if (getSizeExpr()) {
1395    std::string SStr;
1396    llvm::raw_string_ostream s(SStr);
1397    getSizeExpr()->printPretty(s, 0, Policy);
1398    S += s.str();
1399  }
1400  S += ")))";
1401}
1402
1403void VectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1404  // FIXME: We prefer to print the size directly here, but have no way
1405  // to get the size of the type.
1406  S += " __attribute__((__vector_size__(";
1407  S += llvm::utostr_32(NumElements); // convert back to bytes.
1408  S += " * sizeof(" + ElementType.getAsString() + "))))";
1409  ElementType.getAsStringInternal(S, Policy);
1410}
1411
1412void ExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1413  S += " __attribute__((ext_vector_type(";
1414  S += llvm::utostr_32(NumElements);
1415  S += ")))";
1416  ElementType.getAsStringInternal(S, Policy);
1417}
1418
1419void TypeOfExprType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1420  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
1421    InnerString = ' ' + InnerString;
1422  std::string Str;
1423  llvm::raw_string_ostream s(Str);
1424  getUnderlyingExpr()->printPretty(s, 0, Policy);
1425  InnerString = "typeof " + s.str() + InnerString;
1426}
1427
1428void TypeOfType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1429  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
1430    InnerString = ' ' + InnerString;
1431  std::string Tmp;
1432  getUnderlyingType().getAsStringInternal(Tmp, Policy);
1433  InnerString = "typeof(" + Tmp + ")" + InnerString;
1434}
1435
1436void DecltypeType::getAsStringInternal(std::string &InnerString,
1437                                       const PrintingPolicy &Policy) const {
1438  if (!InnerString.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
1439    InnerString = ' ' + InnerString;
1440  std::string Str;
1441  llvm::raw_string_ostream s(Str);
1442  getUnderlyingExpr()->printPretty(s, 0, Policy);
1443  InnerString = "decltype(" + s.str() + ")" + InnerString;
1444}
1445
1446void FunctionNoProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1447  // If needed for precedence reasons, wrap the inner part in grouping parens.
1448  if (!S.empty())
1449    S = "(" + S + ")";
1450
1451  S += "()";
1452  getResultType().getAsStringInternal(S, Policy);
1453}
1454
1455void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1456  // If needed for precedence reasons, wrap the inner part in grouping parens.
1457  if (!S.empty())
1458    S = "(" + S + ")";
1459
1460  S += "(";
1461  std::string Tmp;
1462  PrintingPolicy ParamPolicy(Policy);
1463  ParamPolicy.SuppressSpecifiers = false;
1464  for (unsigned i = 0, e = getNumArgs(); i != e; ++i) {
1465    if (i) S += ", ";
1466    getArgType(i).getAsStringInternal(Tmp, ParamPolicy);
1467    S += Tmp;
1468    Tmp.clear();
1469  }
1470
1471  if (isVariadic()) {
1472    if (getNumArgs())
1473      S += ", ";
1474    S += "...";
1475  } else if (getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
1476    // Do not emit int() if we have a proto, emit 'int(void)'.
1477    S += "void";
1478  }
1479
1480  S += ")";
1481  getResultType().getAsStringInternal(S, Policy);
1482}
1483
1484
1485void TypedefType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1486  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1487    InnerString = ' ' + InnerString;
1488  InnerString = getDecl()->getIdentifier()->getName() + InnerString;
1489}
1490
1491void TemplateTypeParmType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1492  if (!InnerString.empty())    // Prefix the basic type, e.g. 'parmname X'.
1493    InnerString = ' ' + InnerString;
1494
1495  if (!Name)
1496    InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' +
1497      llvm::utostr_32(Index) + InnerString;
1498  else
1499    InnerString = Name->getName() + InnerString;
1500}
1501
1502std::string
1503TemplateSpecializationType::PrintTemplateArgumentList(
1504                                                  const TemplateArgument *Args,
1505                                                  unsigned NumArgs,
1506                                                  const PrintingPolicy &Policy) {
1507  std::string SpecString;
1508  SpecString += '<';
1509  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1510    if (Arg)
1511      SpecString += ", ";
1512
1513    // Print the argument into a string.
1514    std::string ArgString;
1515    switch (Args[Arg].getKind()) {
1516    case TemplateArgument::Null:
1517      assert(false && "Null template argument");
1518      break;
1519
1520    case TemplateArgument::Type:
1521      Args[Arg].getAsType().getAsStringInternal(ArgString, Policy);
1522      break;
1523
1524    case TemplateArgument::Declaration:
1525      ArgString = cast<NamedDecl>(Args[Arg].getAsDecl())->getNameAsString();
1526      break;
1527
1528    case TemplateArgument::Integral:
1529      ArgString = Args[Arg].getAsIntegral()->toString(10, true);
1530      break;
1531
1532    case TemplateArgument::Expression: {
1533      llvm::raw_string_ostream s(ArgString);
1534      Args[Arg].getAsExpr()->printPretty(s, 0, Policy);
1535      break;
1536    }
1537    case TemplateArgument::Pack:
1538      assert(0 && "FIXME: Implement!");
1539      break;
1540    }
1541
1542    // If this is the first argument and its string representation
1543    // begins with the global scope specifier ('::foo'), add a space
1544    // to avoid printing the diagraph '<:'.
1545    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1546      SpecString += ' ';
1547
1548    SpecString += ArgString;
1549  }
1550
1551  // If the last character of our string is '>', add another space to
1552  // keep the two '>''s separate tokens. We don't *have* to do this in
1553  // C++0x, but it's still good hygiene.
1554  if (SpecString[SpecString.size() - 1] == '>')
1555    SpecString += ' ';
1556
1557  SpecString += '>';
1558
1559  return SpecString;
1560}
1561
1562void
1563TemplateSpecializationType::
1564getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1565  std::string SpecString;
1566
1567  {
1568    llvm::raw_string_ostream OS(SpecString);
1569    Template.print(OS, Policy);
1570  }
1571
1572  SpecString += PrintTemplateArgumentList(getArgs(), getNumArgs(), Policy);
1573  if (InnerString.empty())
1574    InnerString.swap(SpecString);
1575  else
1576    InnerString = SpecString + ' ' + InnerString;
1577}
1578
1579void QualifiedNameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1580  std::string MyString;
1581
1582  {
1583    llvm::raw_string_ostream OS(MyString);
1584    NNS->print(OS, Policy);
1585  }
1586
1587  std::string TypeStr;
1588  PrintingPolicy InnerPolicy(Policy);
1589  InnerPolicy.SuppressTagKind = true;
1590  NamedType.getAsStringInternal(TypeStr, InnerPolicy);
1591
1592  MyString += TypeStr;
1593  if (InnerString.empty())
1594    InnerString.swap(MyString);
1595  else
1596    InnerString = MyString + ' ' + InnerString;
1597}
1598
1599void TypenameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1600  std::string MyString;
1601
1602  {
1603    llvm::raw_string_ostream OS(MyString);
1604    OS << "typename ";
1605    NNS->print(OS, Policy);
1606
1607    if (const IdentifierInfo *Ident = getIdentifier())
1608      OS << Ident->getName();
1609    else if (const TemplateSpecializationType *Spec = getTemplateId()) {
1610      Spec->getTemplateName().print(OS, Policy, true);
1611      OS << TemplateSpecializationType::PrintTemplateArgumentList(
1612                                                               Spec->getArgs(),
1613                                                            Spec->getNumArgs(),
1614                                                               Policy);
1615    }
1616  }
1617
1618  if (InnerString.empty())
1619    InnerString.swap(MyString);
1620  else
1621    InnerString = MyString + ' ' + InnerString;
1622}
1623
1624void ObjCInterfaceType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1625  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1626    InnerString = ' ' + InnerString;
1627  InnerString = getDecl()->getIdentifier()->getName() + InnerString;
1628}
1629
1630void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString,
1631                                                const PrintingPolicy &Policy) const {
1632  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1633    InnerString = ' ' + InnerString;
1634
1635  std::string ObjCQIString;
1636
1637  if (getDecl())
1638    ObjCQIString = getDecl()->getNameAsString();
1639  else
1640    ObjCQIString = "id";
1641
1642  if (!qual_empty()) {
1643    ObjCQIString += '<';
1644    for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1645      ObjCQIString += (*I)->getNameAsString();
1646      if (I+1 != E)
1647        ObjCQIString += ',';
1648    }
1649    ObjCQIString += '>';
1650  }
1651  InnerString = ObjCQIString + InnerString;
1652}
1653
1654void
1655ObjCQualifiedInterfaceType::getAsStringInternal(std::string &InnerString,
1656                                           const PrintingPolicy &Policy) const {
1657  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1658    InnerString = ' ' + InnerString;
1659  std::string ObjCQIString = getDecl()->getNameAsString();
1660  ObjCQIString += '<';
1661  bool isFirst = true;
1662  for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1663    if (isFirst)
1664      isFirst = false;
1665    else
1666      ObjCQIString += ',';
1667    ObjCQIString += (*I)->getNameAsString();
1668  }
1669  ObjCQIString += '>';
1670  InnerString = ObjCQIString + InnerString;
1671}
1672
1673void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1674  if (Policy.SuppressTag)
1675    return;
1676
1677  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1678    InnerString = ' ' + InnerString;
1679
1680  const char *Kind = Policy.SuppressTagKind? 0 : getDecl()->getKindName();
1681  const char *ID;
1682  if (const IdentifierInfo *II = getDecl()->getIdentifier())
1683    ID = II->getName();
1684  else if (TypedefDecl *Typedef = getDecl()->getTypedefForAnonDecl()) {
1685    Kind = 0;
1686    assert(Typedef->getIdentifier() && "Typedef without identifier?");
1687    ID = Typedef->getIdentifier()->getName();
1688  } else
1689    ID = "<anonymous>";
1690
1691  // If this is a class template specialization, print the template
1692  // arguments.
1693  if (ClassTemplateSpecializationDecl *Spec
1694        = dyn_cast<ClassTemplateSpecializationDecl>(getDecl())) {
1695    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1696    std::string TemplateArgsStr
1697      = TemplateSpecializationType::PrintTemplateArgumentList(
1698                                            TemplateArgs.getFlatArgumentList(),
1699                                            TemplateArgs.flat_size(),
1700                                                              Policy);
1701    InnerString = TemplateArgsStr + InnerString;
1702  }
1703
1704  if (Kind) {
1705    // Compute the full nested-name-specifier for this type. In C,
1706    // this will always be empty.
1707    std::string ContextStr;
1708    for (DeclContext *DC = getDecl()->getDeclContext();
1709         !DC->isTranslationUnit(); DC = DC->getParent()) {
1710      std::string MyPart;
1711      if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
1712        if (NS->getIdentifier())
1713          MyPart = NS->getNameAsString();
1714      } else if (ClassTemplateSpecializationDecl *Spec
1715                   = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1716        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1717        std::string TemplateArgsStr
1718          = TemplateSpecializationType::PrintTemplateArgumentList(
1719                                           TemplateArgs.getFlatArgumentList(),
1720                                           TemplateArgs.flat_size(),
1721                                           Policy);
1722        MyPart = Spec->getIdentifier()->getName() + TemplateArgsStr;
1723      } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
1724        if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
1725          MyPart = Typedef->getIdentifier()->getName();
1726        else if (Tag->getIdentifier())
1727          MyPart = Tag->getIdentifier()->getName();
1728      }
1729
1730      if (!MyPart.empty())
1731        ContextStr = MyPart + "::" + ContextStr;
1732    }
1733
1734    InnerString = std::string(Kind) + " " + ContextStr + ID + InnerString;
1735  } else
1736    InnerString = ID + InnerString;
1737}
1738