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