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