1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
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 contains code to print types from Clang's type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/PrettyPrinter.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 
26 namespace {
27   /// \brief RAII object that enables printing of the ARC __strong lifetime
28   /// qualifier.
29   class IncludeStrongLifetimeRAII {
30     PrintingPolicy &Policy;
31     bool Old;
32 
33   public:
34     explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
35       : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
36       Policy.SuppressStrongLifetime = false;
37     }
38 
39     ~IncludeStrongLifetimeRAII() {
40       Policy.SuppressStrongLifetime = Old;
41     }
42   };
43 
44   class TypePrinter {
45     PrintingPolicy Policy;
46 
47   public:
48     explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
49 
50     void print(const Type *ty, Qualifiers qs, std::string &buffer);
51     void print(QualType T, std::string &S);
52     void AppendScope(DeclContext *DC, std::string &S);
53     void printTag(TagDecl *T, std::string &S);
54 #define ABSTRACT_TYPE(CLASS, PARENT)
55 #define TYPE(CLASS, PARENT) \
56     void print##CLASS(const CLASS##Type *T, std::string &S);
57 #include "clang/AST/TypeNodes.def"
58   };
59 }
60 
61 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
62   if (TypeQuals & Qualifiers::Const) {
63     if (!S.empty()) S += ' ';
64     S += "const";
65   }
66   if (TypeQuals & Qualifiers::Volatile) {
67     if (!S.empty()) S += ' ';
68     S += "volatile";
69   }
70   if (TypeQuals & Qualifiers::Restrict) {
71     if (!S.empty()) S += ' ';
72     S += "restrict";
73   }
74 }
75 
76 void TypePrinter::print(QualType t, std::string &buffer) {
77   SplitQualType split = t.split();
78   print(split.first, split.second, buffer);
79 }
80 
81 void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
82   if (!T) {
83     buffer += "NULL TYPE";
84     return;
85   }
86 
87   if (Policy.SuppressSpecifiers && T->isSpecifierType())
88     return;
89 
90   // Print qualifiers as appropriate.
91 
92   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
93   // so that we get "const int" instead of "int const", but we can't do this if
94   // the type is complex.  For example if the type is "int*", we *must* print
95   // "int * const", printing "const int *" is different.  Only do this when the
96   // type expands to a simple string.
97   bool CanPrefixQualifiers = false;
98   bool NeedARCStrongQualifier = false;
99   Type::TypeClass TC = T->getTypeClass();
100   if (const AutoType *AT = dyn_cast<AutoType>(T))
101     TC = AT->desugar()->getTypeClass();
102   if (const SubstTemplateTypeParmType *Subst
103                                       = dyn_cast<SubstTemplateTypeParmType>(T))
104     TC = Subst->getReplacementType()->getTypeClass();
105 
106   switch (TC) {
107     case Type::Builtin:
108     case Type::Complex:
109     case Type::UnresolvedUsing:
110     case Type::Typedef:
111     case Type::TypeOfExpr:
112     case Type::TypeOf:
113     case Type::Decltype:
114     case Type::UnaryTransform:
115     case Type::Record:
116     case Type::Enum:
117     case Type::Elaborated:
118     case Type::TemplateTypeParm:
119     case Type::SubstTemplateTypeParmPack:
120     case Type::TemplateSpecialization:
121     case Type::InjectedClassName:
122     case Type::DependentName:
123     case Type::DependentTemplateSpecialization:
124     case Type::ObjCObject:
125     case Type::ObjCInterface:
126     case Type::Atomic:
127       CanPrefixQualifiers = true;
128       break;
129 
130     case Type::ObjCObjectPointer:
131       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
132         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
133       break;
134 
135     case Type::ConstantArray:
136     case Type::IncompleteArray:
137     case Type::VariableArray:
138     case Type::DependentSizedArray:
139       NeedARCStrongQualifier = true;
140       // Fall through
141 
142     case Type::Pointer:
143     case Type::BlockPointer:
144     case Type::LValueReference:
145     case Type::RValueReference:
146     case Type::MemberPointer:
147     case Type::DependentSizedExtVector:
148     case Type::Vector:
149     case Type::ExtVector:
150     case Type::FunctionProto:
151     case Type::FunctionNoProto:
152     case Type::Paren:
153     case Type::Attributed:
154     case Type::PackExpansion:
155     case Type::SubstTemplateTypeParm:
156     case Type::Auto:
157       CanPrefixQualifiers = false;
158       break;
159   }
160 
161   if (!CanPrefixQualifiers && !Quals.empty()) {
162     std::string qualsBuffer;
163     if (NeedARCStrongQualifier) {
164       IncludeStrongLifetimeRAII Strong(Policy);
165       Quals.getAsStringInternal(qualsBuffer, Policy);
166     } else {
167       Quals.getAsStringInternal(qualsBuffer, Policy);
168     }
169 
170     if (!qualsBuffer.empty()) {
171       if (!buffer.empty()) {
172         qualsBuffer += ' ';
173         qualsBuffer += buffer;
174       }
175       std::swap(buffer, qualsBuffer);
176     }
177   }
178 
179   switch (T->getTypeClass()) {
180 #define ABSTRACT_TYPE(CLASS, PARENT)
181 #define TYPE(CLASS, PARENT) case Type::CLASS: \
182     print##CLASS(cast<CLASS##Type>(T), buffer); \
183     break;
184 #include "clang/AST/TypeNodes.def"
185   }
186 
187   // If we're adding the qualifiers as a prefix, do it now.
188   if (CanPrefixQualifiers && !Quals.empty()) {
189     std::string qualsBuffer;
190     if (NeedARCStrongQualifier) {
191       IncludeStrongLifetimeRAII Strong(Policy);
192       Quals.getAsStringInternal(qualsBuffer, Policy);
193     } else {
194       Quals.getAsStringInternal(qualsBuffer, Policy);
195     }
196 
197     if (!qualsBuffer.empty()) {
198       if (!buffer.empty()) {
199         qualsBuffer += ' ';
200         qualsBuffer += buffer;
201       }
202       std::swap(buffer, qualsBuffer);
203     }
204   }
205 }
206 
207 void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
208   if (S.empty()) {
209     S = T->getName(Policy);
210   } else {
211     // Prefix the basic type, e.g. 'int X'.
212     S = ' ' + S;
213     S = T->getName(Policy) + S;
214   }
215 }
216 
217 void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
218   print(T->getElementType(), S);
219   S = "_Complex " + S;
220 }
221 
222 void TypePrinter::printPointer(const PointerType *T, std::string &S) {
223   S = '*' + S;
224 
225   // Handle things like 'int (*A)[4];' correctly.
226   // FIXME: this should include vectors, but vectors use attributes I guess.
227   if (isa<ArrayType>(T->getPointeeType()))
228     S = '(' + S + ')';
229 
230   IncludeStrongLifetimeRAII Strong(Policy);
231   print(T->getPointeeType(), S);
232 }
233 
234 void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
235   S = '^' + S;
236   print(T->getPointeeType(), S);
237 }
238 
239 void TypePrinter::printLValueReference(const LValueReferenceType *T,
240                                        std::string &S) {
241   S = '&' + S;
242 
243   // Handle things like 'int (&A)[4];' correctly.
244   // FIXME: this should include vectors, but vectors use attributes I guess.
245   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
246     S = '(' + S + ')';
247 
248   IncludeStrongLifetimeRAII Strong(Policy);
249   print(T->getPointeeTypeAsWritten(), S);
250 }
251 
252 void TypePrinter::printRValueReference(const RValueReferenceType *T,
253                                        std::string &S) {
254   S = "&&" + S;
255 
256   // Handle things like 'int (&&A)[4];' correctly.
257   // FIXME: this should include vectors, but vectors use attributes I guess.
258   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
259     S = '(' + S + ')';
260 
261   IncludeStrongLifetimeRAII Strong(Policy);
262   print(T->getPointeeTypeAsWritten(), S);
263 }
264 
265 void TypePrinter::printMemberPointer(const MemberPointerType *T,
266                                      std::string &S) {
267   std::string C;
268   print(QualType(T->getClass(), 0), C);
269   C += "::*";
270   S = C + S;
271 
272   // Handle things like 'int (Cls::*A)[4];' correctly.
273   // FIXME: this should include vectors, but vectors use attributes I guess.
274   if (isa<ArrayType>(T->getPointeeType()))
275     S = '(' + S + ')';
276 
277   IncludeStrongLifetimeRAII Strong(Policy);
278   print(T->getPointeeType(), S);
279 }
280 
281 void TypePrinter::printConstantArray(const ConstantArrayType *T,
282                                      std::string &S) {
283   S += '[';
284   S += llvm::utostr(T->getSize().getZExtValue());
285   S += ']';
286 
287   IncludeStrongLifetimeRAII Strong(Policy);
288   print(T->getElementType(), S);
289 }
290 
291 void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
292                                        std::string &S) {
293   S += "[]";
294   IncludeStrongLifetimeRAII Strong(Policy);
295   print(T->getElementType(), S);
296 }
297 
298 void TypePrinter::printVariableArray(const VariableArrayType *T,
299                                      std::string &S) {
300   S += '[';
301 
302   if (T->getIndexTypeQualifiers().hasQualifiers()) {
303     AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
304     S += ' ';
305   }
306 
307   if (T->getSizeModifier() == VariableArrayType::Static)
308     S += "static";
309   else if (T->getSizeModifier() == VariableArrayType::Star)
310     S += '*';
311 
312   if (T->getSizeExpr()) {
313     std::string SStr;
314     llvm::raw_string_ostream s(SStr);
315     T->getSizeExpr()->printPretty(s, 0, Policy);
316     S += s.str();
317   }
318   S += ']';
319 
320   IncludeStrongLifetimeRAII Strong(Policy);
321   print(T->getElementType(), S);
322 }
323 
324 void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T,
325                                            std::string &S) {
326   S += '[';
327 
328   if (T->getSizeExpr()) {
329     std::string SStr;
330     llvm::raw_string_ostream s(SStr);
331     T->getSizeExpr()->printPretty(s, 0, Policy);
332     S += s.str();
333   }
334   S += ']';
335 
336   IncludeStrongLifetimeRAII Strong(Policy);
337   print(T->getElementType(), S);
338 }
339 
340 void TypePrinter::printDependentSizedExtVector(
341                                           const DependentSizedExtVectorType *T,
342                                                std::string &S) {
343   print(T->getElementType(), S);
344 
345   S += " __attribute__((ext_vector_type(";
346   if (T->getSizeExpr()) {
347     std::string SStr;
348     llvm::raw_string_ostream s(SStr);
349     T->getSizeExpr()->printPretty(s, 0, Policy);
350     S += s.str();
351   }
352   S += ")))";
353 }
354 
355 void TypePrinter::printVector(const VectorType *T, std::string &S) {
356   switch (T->getVectorKind()) {
357   case VectorType::AltiVecPixel:
358     S = "__vector __pixel " + S;
359     break;
360   case VectorType::AltiVecBool:
361     print(T->getElementType(), S);
362     S = "__vector __bool " + S;
363     break;
364   case VectorType::AltiVecVector:
365     print(T->getElementType(), S);
366     S = "__vector " + S;
367     break;
368   case VectorType::NeonVector:
369     print(T->getElementType(), S);
370     S = ("__attribute__((neon_vector_type(" +
371          llvm::utostr_32(T->getNumElements()) + "))) " + S);
372     break;
373   case VectorType::NeonPolyVector:
374     print(T->getElementType(), S);
375     S = ("__attribute__((neon_polyvector_type(" +
376          llvm::utostr_32(T->getNumElements()) + "))) " + S);
377     break;
378   case VectorType::GenericVector: {
379     // FIXME: We prefer to print the size directly here, but have no way
380     // to get the size of the type.
381     print(T->getElementType(), S);
382     std::string V = "__attribute__((__vector_size__(";
383     V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
384     std::string ET;
385     print(T->getElementType(), ET);
386     V += " * sizeof(" + ET + ")))) ";
387     S = V + S;
388     break;
389   }
390   }
391 }
392 
393 void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) {
394   S += " __attribute__((ext_vector_type(";
395   S += llvm::utostr_32(T->getNumElements());
396   S += ")))";
397   print(T->getElementType(), S);
398 }
399 
400 void TypePrinter::printFunctionProto(const FunctionProtoType *T,
401                                      std::string &S) {
402   // If needed for precedence reasons, wrap the inner part in grouping parens.
403   if (!S.empty())
404     S = "(" + S + ")";
405 
406   S += "(";
407   std::string Tmp;
408   PrintingPolicy ParamPolicy(Policy);
409   ParamPolicy.SuppressSpecifiers = false;
410   for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
411     if (i) S += ", ";
412     print(T->getArgType(i), Tmp);
413     S += Tmp;
414     Tmp.clear();
415   }
416 
417   if (T->isVariadic()) {
418     if (T->getNumArgs())
419       S += ", ";
420     S += "...";
421   } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
422     // Do not emit int() if we have a proto, emit 'int(void)'.
423     S += "void";
424   }
425 
426   S += ")";
427 
428   FunctionType::ExtInfo Info = T->getExtInfo();
429   switch(Info.getCC()) {
430   case CC_Default: break;
431   case CC_C:
432     S += " __attribute__((cdecl))";
433     break;
434   case CC_X86StdCall:
435     S += " __attribute__((stdcall))";
436     break;
437   case CC_X86FastCall:
438     S += " __attribute__((fastcall))";
439     break;
440   case CC_X86ThisCall:
441     S += " __attribute__((thiscall))";
442     break;
443   case CC_X86Pascal:
444     S += " __attribute__((pascal))";
445     break;
446   case CC_AAPCS:
447     S += " __attribute__((pcs(\"aapcs\")))";
448     break;
449   case CC_AAPCS_VFP:
450     S += " __attribute__((pcs(\"aapcs-vfp\")))";
451     break;
452   }
453   if (Info.getNoReturn())
454     S += " __attribute__((noreturn))";
455   if (Info.getRegParm())
456     S += " __attribute__((regparm (" +
457         llvm::utostr_32(Info.getRegParm()) + ")))";
458 
459   AppendTypeQualList(S, T->getTypeQuals());
460 
461   switch (T->getRefQualifier()) {
462   case RQ_None:
463     break;
464 
465   case RQ_LValue:
466     S += " &";
467     break;
468 
469   case RQ_RValue:
470     S += " &&";
471     break;
472   }
473 
474   if (T->hasDynamicExceptionSpec()) {
475     S += " throw(";
476     if (T->getExceptionSpecType() == EST_MSAny)
477       S += "...";
478     else
479       for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
480         if (I)
481           S += ", ";
482 
483         std::string ExceptionType;
484         print(T->getExceptionType(I), ExceptionType);
485         S += ExceptionType;
486       }
487     S += ")";
488   } else if (isNoexceptExceptionSpec(T->getExceptionSpecType())) {
489     S += " noexcept";
490     if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
491       S += "(";
492       llvm::raw_string_ostream EOut(S);
493       T->getNoexceptExpr()->printPretty(EOut, 0, Policy);
494       EOut.flush();
495       S += EOut.str();
496       S += ")";
497     }
498   }
499 
500   print(T->getResultType(), S);
501 }
502 
503 void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
504                                        std::string &S) {
505   // If needed for precedence reasons, wrap the inner part in grouping parens.
506   if (!S.empty())
507     S = "(" + S + ")";
508 
509   S += "()";
510   if (T->getNoReturnAttr())
511     S += " __attribute__((noreturn))";
512   print(T->getResultType(), S);
513 }
514 
515 static void printTypeSpec(const NamedDecl *D, std::string &S) {
516   IdentifierInfo *II = D->getIdentifier();
517   if (S.empty())
518     S = II->getName().str();
519   else
520     S = II->getName().str() + ' ' + S;
521 }
522 
523 void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
524                                        std::string &S) {
525   printTypeSpec(T->getDecl(), S);
526 }
527 
528 void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
529   printTypeSpec(T->getDecl(), S);
530 }
531 
532 void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
533   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
534     S = ' ' + S;
535   std::string Str;
536   llvm::raw_string_ostream s(Str);
537   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
538   S = "typeof " + s.str() + S;
539 }
540 
541 void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
542   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
543     S = ' ' + S;
544   std::string Tmp;
545   print(T->getUnderlyingType(), Tmp);
546   S = "typeof(" + Tmp + ")" + S;
547 }
548 
549 void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
550   if (!S.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
551     S = ' ' + S;
552   std::string Str;
553   llvm::raw_string_ostream s(Str);
554   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
555   S = "decltype(" + s.str() + ")" + S;
556 }
557 
558 void TypePrinter::printUnaryTransform(const UnaryTransformType *T,
559                                            std::string &S) {
560   if (!S.empty())
561     S = ' ' + S;
562   std::string Str;
563   IncludeStrongLifetimeRAII Strong(Policy);
564   print(T->getBaseType(), Str);
565 
566   switch (T->getUTTKind()) {
567     case UnaryTransformType::EnumUnderlyingType:
568       S = "__underlying_type(" + Str + ")" + S;
569       break;
570   }
571 }
572 
573 void TypePrinter::printAuto(const AutoType *T, std::string &S) {
574   // If the type has been deduced, do not print 'auto'.
575   if (T->isDeduced()) {
576     print(T->getDeducedType(), S);
577   } else {
578     if (!S.empty())    // Prefix the basic type, e.g. 'auto X'.
579       S = ' ' + S;
580     S = "auto" + S;
581   }
582 }
583 
584 void TypePrinter::printAtomic(const AtomicType *T, std::string &S) {
585   if (!S.empty())
586     S = ' ' + S;
587   std::string Str;
588   IncludeStrongLifetimeRAII Strong(Policy);
589   print(T->getValueType(), Str);
590 
591   S = "_Atomic(" + Str + ")" + S;
592 }
593 
594 /// Appends the given scope to the end of a string.
595 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
596   if (DC->isTranslationUnit()) return;
597   AppendScope(DC->getParent(), Buffer);
598 
599   unsigned OldSize = Buffer.size();
600 
601   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
602     if (Policy.SuppressUnwrittenScope &&
603         (NS->isAnonymousNamespace() || NS->isInline()))
604       return;
605     if (NS->getIdentifier())
606       Buffer += NS->getNameAsString();
607     else
608       Buffer += "<anonymous>";
609   } else if (ClassTemplateSpecializationDecl *Spec
610                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
611     IncludeStrongLifetimeRAII Strong(Policy);
612     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
613     std::string TemplateArgsStr
614       = TemplateSpecializationType::PrintTemplateArgumentList(
615                                             TemplateArgs.data(),
616                                             TemplateArgs.size(),
617                                             Policy);
618     Buffer += Spec->getIdentifier()->getName();
619     Buffer += TemplateArgsStr;
620   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
621     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
622       Buffer += Typedef->getIdentifier()->getName();
623     else if (Tag->getIdentifier())
624       Buffer += Tag->getIdentifier()->getName();
625     else
626       return;
627   }
628 
629   if (Buffer.size() != OldSize)
630     Buffer += "::";
631 }
632 
633 void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
634   if (Policy.SuppressTag)
635     return;
636 
637   std::string Buffer;
638   bool HasKindDecoration = false;
639 
640   // bool SuppressTagKeyword
641   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
642 
643   // We don't print tags unless this is an elaborated type.
644   // In C, we just assume every RecordType is an elaborated type.
645   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
646         D->getTypedefNameForAnonDecl())) {
647     HasKindDecoration = true;
648     Buffer += D->getKindName();
649     Buffer += ' ';
650   }
651 
652   // Compute the full nested-name-specifier for this type.
653   // In C, this will always be empty except when the type
654   // being printed is anonymous within other Record.
655   if (!Policy.SuppressScope)
656     AppendScope(D->getDeclContext(), Buffer);
657 
658   if (const IdentifierInfo *II = D->getIdentifier())
659     Buffer += II->getNameStart();
660   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
661     assert(Typedef->getIdentifier() && "Typedef without identifier?");
662     Buffer += Typedef->getIdentifier()->getNameStart();
663   } else {
664     // Make an unambiguous representation for anonymous types, e.g.
665     //   <anonymous enum at /usr/include/string.h:120:9>
666     llvm::raw_string_ostream OS(Buffer);
667     OS << "<anonymous";
668 
669     if (Policy.AnonymousTagLocations) {
670       // Suppress the redundant tag keyword if we just printed one.
671       // We don't have to worry about ElaboratedTypes here because you can't
672       // refer to an anonymous type with one.
673       if (!HasKindDecoration)
674         OS << " " << D->getKindName();
675 
676       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
677           D->getLocation());
678       if (PLoc.isValid()) {
679         OS << " at " << PLoc.getFilename()
680            << ':' << PLoc.getLine()
681            << ':' << PLoc.getColumn();
682       }
683     }
684 
685     OS << '>';
686   }
687 
688   // If this is a class template specialization, print the template
689   // arguments.
690   if (ClassTemplateSpecializationDecl *Spec
691         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
692     const TemplateArgument *Args;
693     unsigned NumArgs;
694     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
695       const TemplateSpecializationType *TST =
696         cast<TemplateSpecializationType>(TAW->getType());
697       Args = TST->getArgs();
698       NumArgs = TST->getNumArgs();
699     } else {
700       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
701       Args = TemplateArgs.data();
702       NumArgs = TemplateArgs.size();
703     }
704     IncludeStrongLifetimeRAII Strong(Policy);
705     Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
706                                                                     NumArgs,
707                                                                     Policy);
708   }
709 
710   if (!InnerString.empty()) {
711     Buffer += ' ';
712     Buffer += InnerString;
713   }
714 
715   std::swap(Buffer, InnerString);
716 }
717 
718 void TypePrinter::printRecord(const RecordType *T, std::string &S) {
719   printTag(T->getDecl(), S);
720 }
721 
722 void TypePrinter::printEnum(const EnumType *T, std::string &S) {
723   printTag(T->getDecl(), S);
724 }
725 
726 void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
727                                         std::string &S) {
728   if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
729     S = ' ' + S;
730 
731   if (IdentifierInfo *Id = T->getIdentifier())
732     S = Id->getName().str() + S;
733   else
734     S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
735         llvm::utostr_32(T->getIndex()) + S;
736 }
737 
738 void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
739                                              std::string &S) {
740   IncludeStrongLifetimeRAII Strong(Policy);
741   print(T->getReplacementType(), S);
742 }
743 
744 void TypePrinter::printSubstTemplateTypeParmPack(
745                                         const SubstTemplateTypeParmPackType *T,
746                                              std::string &S) {
747   IncludeStrongLifetimeRAII Strong(Policy);
748   printTemplateTypeParm(T->getReplacedParameter(), S);
749 }
750 
751 void TypePrinter::printTemplateSpecialization(
752                                             const TemplateSpecializationType *T,
753                                               std::string &S) {
754   IncludeStrongLifetimeRAII Strong(Policy);
755   std::string SpecString;
756 
757   {
758     llvm::raw_string_ostream OS(SpecString);
759     T->getTemplateName().print(OS, Policy);
760   }
761 
762   SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
763                                                                   T->getArgs(),
764                                                                 T->getNumArgs(),
765                                                                       Policy);
766   if (S.empty())
767     S.swap(SpecString);
768   else
769     S = SpecString + ' ' + S;
770 }
771 
772 void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
773                                          std::string &S) {
774   printTemplateSpecialization(T->getInjectedTST(), S);
775 }
776 
777 void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
778   std::string MyString;
779 
780   {
781     llvm::raw_string_ostream OS(MyString);
782     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
783     if (T->getKeyword() != ETK_None)
784       OS << " ";
785     NestedNameSpecifier* Qualifier = T->getQualifier();
786     if (Qualifier)
787       Qualifier->print(OS, Policy);
788   }
789 
790   std::string TypeStr;
791   PrintingPolicy InnerPolicy(Policy);
792   InnerPolicy.SuppressTagKeyword = true;
793   InnerPolicy.SuppressScope = true;
794   TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
795 
796   MyString += TypeStr;
797   if (S.empty())
798     S.swap(MyString);
799   else
800     S = MyString + ' ' + S;
801 }
802 
803 void TypePrinter::printParen(const ParenType *T, std::string &S) {
804   if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
805     S = '(' + S + ')';
806   print(T->getInnerType(), S);
807 }
808 
809 void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
810   std::string MyString;
811 
812   {
813     llvm::raw_string_ostream OS(MyString);
814     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
815     if (T->getKeyword() != ETK_None)
816       OS << " ";
817 
818     T->getQualifier()->print(OS, Policy);
819 
820     OS << T->getIdentifier()->getName();
821   }
822 
823   if (S.empty())
824     S.swap(MyString);
825   else
826     S = MyString + ' ' + S;
827 }
828 
829 void TypePrinter::printDependentTemplateSpecialization(
830         const DependentTemplateSpecializationType *T, std::string &S) {
831   IncludeStrongLifetimeRAII Strong(Policy);
832   std::string MyString;
833   {
834     llvm::raw_string_ostream OS(MyString);
835 
836     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
837     if (T->getKeyword() != ETK_None)
838       OS << " ";
839 
840     if (T->getQualifier())
841       T->getQualifier()->print(OS, Policy);
842     OS << T->getIdentifier()->getName();
843     OS << TemplateSpecializationType::PrintTemplateArgumentList(
844                                                             T->getArgs(),
845                                                             T->getNumArgs(),
846                                                             Policy);
847   }
848 
849   if (S.empty())
850     S.swap(MyString);
851   else
852     S = MyString + ' ' + S;
853 }
854 
855 void TypePrinter::printPackExpansion(const PackExpansionType *T,
856                                      std::string &S) {
857   print(T->getPattern(), S);
858   S += "...";
859 }
860 
861 void TypePrinter::printAttributed(const AttributedType *T,
862                                   std::string &S) {
863   // Prefer the macro forms of the GC and ownership qualifiers.
864   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
865       T->getAttrKind() == AttributedType::attr_objc_ownership)
866     return print(T->getEquivalentType(), S);
867 
868   print(T->getModifiedType(), S);
869 
870   // TODO: not all attributes are GCC-style attributes.
871   S += " __attribute__((";
872   switch (T->getAttrKind()) {
873   case AttributedType::attr_address_space:
874     S += "address_space(";
875     S += T->getEquivalentType().getAddressSpace();
876     S += ")";
877     break;
878 
879   case AttributedType::attr_vector_size: {
880     S += "__vector_size__(";
881     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
882       S += vector->getNumElements();
883       S += " * sizeof(";
884 
885       std::string tmp;
886       print(vector->getElementType(), tmp);
887       S += tmp;
888       S += ")";
889     }
890     S += ")";
891     break;
892   }
893 
894   case AttributedType::attr_neon_vector_type:
895   case AttributedType::attr_neon_polyvector_type: {
896     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
897       S += "neon_vector_type(";
898     else
899       S += "neon_polyvector_type(";
900     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
901     S += llvm::utostr_32(vector->getNumElements());
902     S += ")";
903     break;
904   }
905 
906   case AttributedType::attr_regparm: {
907     S += "regparm(";
908     QualType t = T->getEquivalentType();
909     while (!t->isFunctionType())
910       t = t->getPointeeType();
911     S += t->getAs<FunctionType>()->getRegParmType();
912     S += ")";
913     break;
914   }
915 
916   case AttributedType::attr_objc_gc: {
917     S += "objc_gc(";
918 
919     QualType tmp = T->getEquivalentType();
920     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
921       QualType next = tmp->getPointeeType();
922       if (next == tmp) break;
923       tmp = next;
924     }
925 
926     if (tmp.isObjCGCWeak())
927       S += "weak";
928     else
929       S += "strong";
930     S += ")";
931     break;
932   }
933 
934   case AttributedType::attr_objc_ownership:
935     S += "objc_ownership(";
936     switch (T->getEquivalentType().getObjCLifetime()) {
937     case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
938     case Qualifiers::OCL_ExplicitNone: S += "none"; break;
939     case Qualifiers::OCL_Strong: S += "strong"; break;
940     case Qualifiers::OCL_Weak: S += "weak"; break;
941     case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
942     }
943     S += ")";
944     break;
945 
946   case AttributedType::attr_noreturn: S += "noreturn"; break;
947   case AttributedType::attr_cdecl: S += "cdecl"; break;
948   case AttributedType::attr_fastcall: S += "fastcall"; break;
949   case AttributedType::attr_stdcall: S += "stdcall"; break;
950   case AttributedType::attr_thiscall: S += "thiscall"; break;
951   case AttributedType::attr_pascal: S += "pascal"; break;
952   case AttributedType::attr_pcs: {
953    S += "pcs(";
954    QualType t = T->getEquivalentType();
955    while (!t->isFunctionType())
956      t = t->getPointeeType();
957    S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
958          "\"aapcs\"" : "\"aapcs-vfp\"");
959    S += ")";
960    break;
961   }
962   }
963   S += "))";
964 }
965 
966 void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
967                                      std::string &S) {
968   if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
969     S = ' ' + S;
970 
971   std::string ObjCQIString = T->getDecl()->getNameAsString();
972   S = ObjCQIString + S;
973 }
974 
975 void TypePrinter::printObjCObject(const ObjCObjectType *T,
976                                   std::string &S) {
977   if (T->qual_empty())
978     return print(T->getBaseType(), S);
979 
980   std::string tmp;
981   print(T->getBaseType(), tmp);
982   tmp += '<';
983   bool isFirst = true;
984   for (ObjCObjectType::qual_iterator
985          I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
986     if (isFirst)
987       isFirst = false;
988     else
989       tmp += ',';
990     tmp += (*I)->getNameAsString();
991   }
992   tmp += '>';
993 
994   if (!S.empty()) {
995     tmp += ' ';
996     tmp += S;
997   }
998   std::swap(tmp, S);
999 }
1000 
1001 void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
1002                                          std::string &S) {
1003   std::string ObjCQIString;
1004 
1005   T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
1006                                                                Policy);
1007   if (!ObjCQIString.empty())
1008     ObjCQIString += ' ';
1009 
1010   if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1011     ObjCQIString += "id";
1012   else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1013     ObjCQIString += "Class";
1014   else if (T->isObjCSelType())
1015     ObjCQIString += "SEL";
1016   else
1017     ObjCQIString += T->getInterfaceDecl()->getNameAsString();
1018 
1019   if (!T->qual_empty()) {
1020     ObjCQIString += '<';
1021     for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1022                                               E = T->qual_end();
1023          I != E; ++I) {
1024       ObjCQIString += (*I)->getNameAsString();
1025       if (I+1 != E)
1026         ObjCQIString += ',';
1027     }
1028     ObjCQIString += '>';
1029   }
1030 
1031   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
1032     ObjCQIString += " *"; // Don't forget the implicit pointer.
1033   else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1034     S = ' ' + S;
1035 
1036   S = ObjCQIString + S;
1037 }
1038 
1039 std::string TemplateSpecializationType::
1040   PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
1041                             const PrintingPolicy &Policy) {
1042   return PrintTemplateArgumentList(Args.getArgumentArray(),
1043                                    Args.size(),
1044                                    Policy);
1045 }
1046 
1047 std::string
1048 TemplateSpecializationType::PrintTemplateArgumentList(
1049                                                 const TemplateArgument *Args,
1050                                                 unsigned NumArgs,
1051                                                   const PrintingPolicy &Policy,
1052                                                       bool SkipBrackets) {
1053   std::string SpecString;
1054   if (!SkipBrackets)
1055     SpecString += '<';
1056 
1057   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1058     if (SpecString.size() > unsigned(!SkipBrackets))
1059       SpecString += ", ";
1060 
1061     // Print the argument into a string.
1062     std::string ArgString;
1063     if (Args[Arg].getKind() == TemplateArgument::Pack) {
1064       ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
1065                                             Args[Arg].pack_size(),
1066                                             Policy, true);
1067     } else {
1068       llvm::raw_string_ostream ArgOut(ArgString);
1069       Args[Arg].print(Policy, ArgOut);
1070     }
1071 
1072     // If this is the first argument and its string representation
1073     // begins with the global scope specifier ('::foo'), add a space
1074     // to avoid printing the diagraph '<:'.
1075     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1076       SpecString += ' ';
1077 
1078     SpecString += ArgString;
1079   }
1080 
1081   // If the last character of our string is '>', add another space to
1082   // keep the two '>''s separate tokens. We don't *have* to do this in
1083   // C++0x, but it's still good hygiene.
1084   if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
1085     SpecString += ' ';
1086 
1087   if (!SkipBrackets)
1088     SpecString += '>';
1089 
1090   return SpecString;
1091 }
1092 
1093 // Sadly, repeat all that with TemplateArgLoc.
1094 std::string TemplateSpecializationType::
1095 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1096                           const PrintingPolicy &Policy) {
1097   std::string SpecString;
1098   SpecString += '<';
1099   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1100     if (SpecString.size() > 1)
1101       SpecString += ", ";
1102 
1103     // Print the argument into a string.
1104     std::string ArgString;
1105     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1106       ArgString = PrintTemplateArgumentList(
1107                                            Args[Arg].getArgument().pack_begin(),
1108                                             Args[Arg].getArgument().pack_size(),
1109                                             Policy, true);
1110     } else {
1111       llvm::raw_string_ostream ArgOut(ArgString);
1112       Args[Arg].getArgument().print(Policy, ArgOut);
1113     }
1114 
1115     // If this is the first argument and its string representation
1116     // begins with the global scope specifier ('::foo'), add a space
1117     // to avoid printing the diagraph '<:'.
1118     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1119       SpecString += ' ';
1120 
1121     SpecString += ArgString;
1122   }
1123 
1124   // If the last character of our string is '>', add another space to
1125   // keep the two '>''s separate tokens. We don't *have* to do this in
1126   // C++0x, but it's still good hygiene.
1127   if (SpecString[SpecString.size() - 1] == '>')
1128     SpecString += ' ';
1129 
1130   SpecString += '>';
1131 
1132   return SpecString;
1133 }
1134 
1135 void QualType::dump(const char *msg) const {
1136   std::string R = "identifier";
1137   LangOptions LO;
1138   getAsStringInternal(R, PrintingPolicy(LO));
1139   if (msg)
1140     llvm::errs() << msg << ": ";
1141   llvm::errs() << R << "\n";
1142 }
1143 void QualType::dump() const {
1144   dump("");
1145 }
1146 
1147 void Type::dump() const {
1148   QualType(this, 0).dump();
1149 }
1150 
1151 std::string Qualifiers::getAsString() const {
1152   LangOptions LO;
1153   return getAsString(PrintingPolicy(LO));
1154 }
1155 
1156 // Appends qualifiers to the given string, separated by spaces.  Will
1157 // prefix a space if the string is non-empty.  Will not append a final
1158 // space.
1159 void Qualifiers::getAsStringInternal(std::string &S,
1160                                      const PrintingPolicy& Policy) const {
1161   AppendTypeQualList(S, getCVRQualifiers());
1162   if (unsigned addrspace = getAddressSpace()) {
1163     if (!S.empty()) S += ' ';
1164     switch (addrspace) {
1165       case LangAS::opencl_global:
1166         S += "__global";
1167         break;
1168       case LangAS::opencl_local:
1169         S += "__local";
1170         break;
1171       case LangAS::opencl_constant:
1172         S += "__constant";
1173         break;
1174       default:
1175         S += "__attribute__((address_space(";
1176         S += llvm::utostr_32(addrspace);
1177         S += ")))";
1178     }
1179   }
1180   if (Qualifiers::GC gc = getObjCGCAttr()) {
1181     if (!S.empty()) S += ' ';
1182     if (gc == Qualifiers::Weak)
1183       S += "__weak";
1184     else
1185       S += "__strong";
1186   }
1187   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1188     if (!S.empty() &&
1189         !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1190       S += ' ';
1191 
1192     switch (lifetime) {
1193     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1194     case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
1195     case Qualifiers::OCL_Strong:
1196       if (!Policy.SuppressStrongLifetime)
1197         S += "__strong";
1198       break;
1199 
1200     case Qualifiers::OCL_Weak: S += "__weak"; break;
1201     case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
1202     }
1203   }
1204 }
1205 
1206 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1207   std::string buffer;
1208   LangOptions options;
1209   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1210   return buffer;
1211 }
1212 
1213 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1214                                    std::string &buffer,
1215                                    const PrintingPolicy &policy) {
1216   TypePrinter(policy).print(ty, qs, buffer);
1217 }
1218