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