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