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