]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/AST/TypePrinter.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / AST / TypePrinter.cpp
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       CanPrefixQualifiers = true;
127       break;
128       
129     case Type::ObjCObjectPointer:
130       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
131         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
132       break;
133       
134     case Type::ConstantArray:
135     case Type::IncompleteArray:
136     case Type::VariableArray:
137     case Type::DependentSizedArray:
138       NeedARCStrongQualifier = true;
139       // Fall through
140       
141     case Type::Pointer:
142     case Type::BlockPointer:
143     case Type::LValueReference:
144     case Type::RValueReference:
145     case Type::MemberPointer:
146     case Type::DependentSizedExtVector:
147     case Type::Vector:
148     case Type::ExtVector:
149     case Type::FunctionProto:
150     case Type::FunctionNoProto:
151     case Type::Paren:
152     case Type::Attributed:
153     case Type::PackExpansion:
154     case Type::SubstTemplateTypeParm:
155     case Type::Auto:
156       CanPrefixQualifiers = false;
157       break;
158   }
159   
160   if (!CanPrefixQualifiers && !Quals.empty()) {
161     std::string qualsBuffer;
162     if (NeedARCStrongQualifier) {
163       IncludeStrongLifetimeRAII Strong(Policy);
164       Quals.getAsStringInternal(qualsBuffer, Policy);
165     } else {
166       Quals.getAsStringInternal(qualsBuffer, Policy);
167     }
168     
169     if (!qualsBuffer.empty()) {
170       if (!buffer.empty()) {
171         qualsBuffer += ' ';
172         qualsBuffer += buffer;
173       }
174       std::swap(buffer, qualsBuffer);
175     }
176   }
177   
178   switch (T->getTypeClass()) {
179 #define ABSTRACT_TYPE(CLASS, PARENT)
180 #define TYPE(CLASS, PARENT) case Type::CLASS: \
181     print##CLASS(cast<CLASS##Type>(T), buffer); \
182     break;
183 #include "clang/AST/TypeNodes.def"
184   }
185   
186   // If we're adding the qualifiers as a prefix, do it now.
187   if (CanPrefixQualifiers && !Quals.empty()) {
188     std::string qualsBuffer;
189     if (NeedARCStrongQualifier) {
190       IncludeStrongLifetimeRAII Strong(Policy);
191       Quals.getAsStringInternal(qualsBuffer, Policy);
192     } else {
193       Quals.getAsStringInternal(qualsBuffer, Policy);
194     }
195
196     if (!qualsBuffer.empty()) {
197       if (!buffer.empty()) {
198         qualsBuffer += ' ';
199         qualsBuffer += buffer;
200       }
201       std::swap(buffer, qualsBuffer);
202     }
203   }
204 }
205
206 void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
207   if (S.empty()) {
208     S = T->getName(Policy.LangOpts);
209   } else {
210     // Prefix the basic type, e.g. 'int X'.
211     S = ' ' + S;
212     S = T->getName(Policy.LangOpts) + S;
213   }
214 }
215
216 void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
217   print(T->getElementType(), S);
218   S = "_Complex " + S;
219 }
220
221 void TypePrinter::printPointer(const PointerType *T, std::string &S) { 
222   S = '*' + S;
223   
224   // Handle things like 'int (*A)[4];' correctly.
225   // FIXME: this should include vectors, but vectors use attributes I guess.
226   if (isa<ArrayType>(T->getPointeeType()))
227     S = '(' + S + ')';
228   
229   IncludeStrongLifetimeRAII Strong(Policy);
230   print(T->getPointeeType(), S);
231 }
232
233 void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
234   S = '^' + S;
235   print(T->getPointeeType(), S);
236 }
237
238 void TypePrinter::printLValueReference(const LValueReferenceType *T, 
239                                        std::string &S) { 
240   S = '&' + S;
241   
242   // Handle things like 'int (&A)[4];' correctly.
243   // FIXME: this should include vectors, but vectors use attributes I guess.
244   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
245     S = '(' + S + ')';
246   
247   IncludeStrongLifetimeRAII Strong(Policy);
248   print(T->getPointeeTypeAsWritten(), S);
249 }
250
251 void TypePrinter::printRValueReference(const RValueReferenceType *T, 
252                                        std::string &S) { 
253   S = "&&" + S;
254   
255   // Handle things like 'int (&&A)[4];' correctly.
256   // FIXME: this should include vectors, but vectors use attributes I guess.
257   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
258     S = '(' + S + ')';
259   
260   IncludeStrongLifetimeRAII Strong(Policy);
261   print(T->getPointeeTypeAsWritten(), S);
262 }
263
264 void TypePrinter::printMemberPointer(const MemberPointerType *T, 
265                                      std::string &S) { 
266   std::string C;
267   print(QualType(T->getClass(), 0), C);
268   C += "::*";
269   S = C + S;
270   
271   // Handle things like 'int (Cls::*A)[4];' correctly.
272   // FIXME: this should include vectors, but vectors use attributes I guess.
273   if (isa<ArrayType>(T->getPointeeType()))
274     S = '(' + S + ')';
275   
276   IncludeStrongLifetimeRAII Strong(Policy);
277   print(T->getPointeeType(), S);
278 }
279
280 void TypePrinter::printConstantArray(const ConstantArrayType *T, 
281                                      std::string &S) {
282   S += '[';
283   S += llvm::utostr(T->getSize().getZExtValue());
284   S += ']';
285   
286   IncludeStrongLifetimeRAII Strong(Policy);
287   print(T->getElementType(), S);
288 }
289
290 void TypePrinter::printIncompleteArray(const IncompleteArrayType *T, 
291                                        std::string &S) {
292   S += "[]";
293   IncludeStrongLifetimeRAII Strong(Policy);
294   print(T->getElementType(), S);
295 }
296
297 void TypePrinter::printVariableArray(const VariableArrayType *T, 
298                                      std::string &S) { 
299   S += '[';
300   
301   if (T->getIndexTypeQualifiers().hasQualifiers()) {
302     AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
303     S += ' ';
304   }
305   
306   if (T->getSizeModifier() == VariableArrayType::Static)
307     S += "static";
308   else if (T->getSizeModifier() == VariableArrayType::Star)
309     S += '*';
310   
311   if (T->getSizeExpr()) {
312     std::string SStr;
313     llvm::raw_string_ostream s(SStr);
314     T->getSizeExpr()->printPretty(s, 0, Policy);
315     S += s.str();
316   }
317   S += ']';
318   
319   IncludeStrongLifetimeRAII Strong(Policy);
320   print(T->getElementType(), S);
321 }
322
323 void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T, 
324                                            std::string &S) {  
325   S += '[';
326   
327   if (T->getSizeExpr()) {
328     std::string SStr;
329     llvm::raw_string_ostream s(SStr);
330     T->getSizeExpr()->printPretty(s, 0, Policy);
331     S += s.str();
332   }
333   S += ']';
334   
335   IncludeStrongLifetimeRAII Strong(Policy);
336   print(T->getElementType(), S);
337 }
338
339 void TypePrinter::printDependentSizedExtVector(
340                                           const DependentSizedExtVectorType *T, 
341                                                std::string &S) { 
342   print(T->getElementType(), S);
343   
344   S += " __attribute__((ext_vector_type(";
345   if (T->getSizeExpr()) {
346     std::string SStr;
347     llvm::raw_string_ostream s(SStr);
348     T->getSizeExpr()->printPretty(s, 0, Policy);
349     S += s.str();
350   }
351   S += ")))";  
352 }
353
354 void TypePrinter::printVector(const VectorType *T, std::string &S) { 
355   switch (T->getVectorKind()) {
356   case VectorType::AltiVecPixel:
357     S = "__vector __pixel " + S;
358     break;
359   case VectorType::AltiVecBool:
360     print(T->getElementType(), S);
361     S = "__vector __bool " + S;
362     break;
363   case VectorType::AltiVecVector:
364     print(T->getElementType(), S);
365     S = "__vector " + S;
366     break;
367   case VectorType::NeonVector:
368     print(T->getElementType(), S);
369     S = ("__attribute__((neon_vector_type(" +
370          llvm::utostr_32(T->getNumElements()) + "))) " + S);
371     break;
372   case VectorType::NeonPolyVector:
373     print(T->getElementType(), S);
374     S = ("__attribute__((neon_polyvector_type(" +
375          llvm::utostr_32(T->getNumElements()) + "))) " + S);
376     break;
377   case VectorType::GenericVector: {
378     // FIXME: We prefer to print the size directly here, but have no way
379     // to get the size of the type.
380     print(T->getElementType(), S);
381     std::string V = "__attribute__((__vector_size__(";
382     V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
383     std::string ET;
384     print(T->getElementType(), ET);
385     V += " * sizeof(" + ET + ")))) ";
386     S = V + S;
387     break;
388   }
389   }
390 }
391
392 void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) { 
393   S += " __attribute__((ext_vector_type(";
394   S += llvm::utostr_32(T->getNumElements());
395   S += ")))";
396   print(T->getElementType(), S);
397 }
398
399 void TypePrinter::printFunctionProto(const FunctionProtoType *T, 
400                                      std::string &S) { 
401   // If needed for precedence reasons, wrap the inner part in grouping parens.
402   if (!S.empty())
403     S = "(" + S + ")";
404   
405   S += "(";
406   std::string Tmp;
407   PrintingPolicy ParamPolicy(Policy);
408   ParamPolicy.SuppressSpecifiers = false;
409   for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
410     if (i) S += ", ";
411     print(T->getArgType(i), Tmp);
412     S += Tmp;
413     Tmp.clear();
414   }
415   
416   if (T->isVariadic()) {
417     if (T->getNumArgs())
418       S += ", ";
419     S += "...";
420   } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
421     // Do not emit int() if we have a proto, emit 'int(void)'.
422     S += "void";
423   }
424   
425   S += ")";
426
427   FunctionType::ExtInfo Info = T->getExtInfo();
428   switch(Info.getCC()) {
429   case CC_Default:
430   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 /// Appends the given scope to the end of a string.
585 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
586   if (DC->isTranslationUnit()) return;
587   AppendScope(DC->getParent(), Buffer);
588
589   unsigned OldSize = Buffer.size();
590
591   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
592     if (NS->getIdentifier())
593       Buffer += NS->getNameAsString();
594     else
595       Buffer += "<anonymous>";
596   } else if (ClassTemplateSpecializationDecl *Spec
597                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
598     IncludeStrongLifetimeRAII Strong(Policy);
599     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
600     std::string TemplateArgsStr
601       = TemplateSpecializationType::PrintTemplateArgumentList(
602                                             TemplateArgs.data(),
603                                             TemplateArgs.size(),
604                                             Policy);
605     Buffer += Spec->getIdentifier()->getName();
606     Buffer += TemplateArgsStr;
607   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
608     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
609       Buffer += Typedef->getIdentifier()->getName();
610     else if (Tag->getIdentifier())
611       Buffer += Tag->getIdentifier()->getName();
612   }
613
614   if (Buffer.size() != OldSize)
615     Buffer += "::";
616 }
617
618 void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
619   if (Policy.SuppressTag)
620     return;
621
622   std::string Buffer;
623   bool HasKindDecoration = false;
624
625   // bool SuppressTagKeyword
626   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
627
628   // We don't print tags unless this is an elaborated type.
629   // In C, we just assume every RecordType is an elaborated type.
630   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
631         D->getTypedefNameForAnonDecl())) {
632     HasKindDecoration = true;
633     Buffer += D->getKindName();
634     Buffer += ' ';
635   }
636
637   // Compute the full nested-name-specifier for this type.
638   // In C, this will always be empty except when the type
639   // being printed is anonymous within other Record.
640   if (!Policy.SuppressScope)
641     AppendScope(D->getDeclContext(), Buffer);
642
643   if (const IdentifierInfo *II = D->getIdentifier())
644     Buffer += II->getNameStart();
645   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
646     assert(Typedef->getIdentifier() && "Typedef without identifier?");
647     Buffer += Typedef->getIdentifier()->getNameStart();
648   } else {
649     // Make an unambiguous representation for anonymous types, e.g.
650     //   <anonymous enum at /usr/include/string.h:120:9>
651     llvm::raw_string_ostream OS(Buffer);
652     OS << "<anonymous";
653
654     if (Policy.AnonymousTagLocations) {
655       // Suppress the redundant tag keyword if we just printed one.
656       // We don't have to worry about ElaboratedTypes here because you can't
657       // refer to an anonymous type with one.
658       if (!HasKindDecoration)
659         OS << " " << D->getKindName();
660
661       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
662           D->getLocation());
663       if (PLoc.isValid()) {
664         OS << " at " << PLoc.getFilename()
665            << ':' << PLoc.getLine()
666            << ':' << PLoc.getColumn();
667       }
668     }
669     
670     OS << '>';
671   }
672
673   // If this is a class template specialization, print the template
674   // arguments.
675   if (ClassTemplateSpecializationDecl *Spec
676         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
677     const TemplateArgument *Args;
678     unsigned NumArgs;
679     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
680       const TemplateSpecializationType *TST =
681         cast<TemplateSpecializationType>(TAW->getType());
682       Args = TST->getArgs();
683       NumArgs = TST->getNumArgs();
684     } else {
685       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
686       Args = TemplateArgs.data();
687       NumArgs = TemplateArgs.size();
688     }
689     IncludeStrongLifetimeRAII Strong(Policy);
690     Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
691                                                                     NumArgs,
692                                                                     Policy);
693   }
694
695   if (!InnerString.empty()) {
696     Buffer += ' ';
697     Buffer += InnerString;
698   }
699
700   std::swap(Buffer, InnerString);
701 }
702
703 void TypePrinter::printRecord(const RecordType *T, std::string &S) {
704   printTag(T->getDecl(), S);
705 }
706
707 void TypePrinter::printEnum(const EnumType *T, std::string &S) { 
708   printTag(T->getDecl(), S);
709 }
710
711 void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T, 
712                                         std::string &S) { 
713   if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
714     S = ' ' + S;
715
716   if (IdentifierInfo *Id = T->getIdentifier())
717     S = Id->getName().str() + S;
718   else
719     S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
720         llvm::utostr_32(T->getIndex()) + S;
721 }
722
723 void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T, 
724                                              std::string &S) { 
725   IncludeStrongLifetimeRAII Strong(Policy);
726   print(T->getReplacementType(), S);
727 }
728
729 void TypePrinter::printSubstTemplateTypeParmPack(
730                                         const SubstTemplateTypeParmPackType *T, 
731                                              std::string &S) { 
732   IncludeStrongLifetimeRAII Strong(Policy);
733   printTemplateTypeParm(T->getReplacedParameter(), S);
734 }
735
736 void TypePrinter::printTemplateSpecialization(
737                                             const TemplateSpecializationType *T, 
738                                               std::string &S) { 
739   IncludeStrongLifetimeRAII Strong(Policy);
740   std::string SpecString;
741   
742   {
743     llvm::raw_string_ostream OS(SpecString);
744     T->getTemplateName().print(OS, Policy);
745   }
746   
747   SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
748                                                                   T->getArgs(), 
749                                                                 T->getNumArgs(), 
750                                                                       Policy);
751   if (S.empty())
752     S.swap(SpecString);
753   else
754     S = SpecString + ' ' + S;
755 }
756
757 void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
758                                          std::string &S) {
759   printTemplateSpecialization(T->getInjectedTST(), S);
760 }
761
762 void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
763   std::string MyString;
764   
765   {
766     llvm::raw_string_ostream OS(MyString);
767     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
768     if (T->getKeyword() != ETK_None)
769       OS << " ";
770     NestedNameSpecifier* Qualifier = T->getQualifier();
771     if (Qualifier)
772       Qualifier->print(OS, Policy);
773   }
774   
775   std::string TypeStr;
776   PrintingPolicy InnerPolicy(Policy);
777   InnerPolicy.SuppressTagKeyword = true;
778   InnerPolicy.SuppressScope = true;
779   TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
780   
781   MyString += TypeStr;
782   if (S.empty())
783     S.swap(MyString);
784   else
785     S = MyString + ' ' + S;  
786 }
787
788 void TypePrinter::printParen(const ParenType *T, std::string &S) {
789   if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
790     S = '(' + S + ')';
791   print(T->getInnerType(), S);
792 }
793
794 void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) { 
795   std::string MyString;
796   
797   {
798     llvm::raw_string_ostream OS(MyString);
799     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
800     if (T->getKeyword() != ETK_None)
801       OS << " ";
802     
803     T->getQualifier()->print(OS, Policy);
804     
805     OS << T->getIdentifier()->getName();
806   }
807   
808   if (S.empty())
809     S.swap(MyString);
810   else
811     S = MyString + ' ' + S;
812 }
813
814 void TypePrinter::printDependentTemplateSpecialization(
815         const DependentTemplateSpecializationType *T, std::string &S) { 
816   IncludeStrongLifetimeRAII Strong(Policy);
817   std::string MyString;
818   {
819     llvm::raw_string_ostream OS(MyString);
820   
821     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
822     if (T->getKeyword() != ETK_None)
823       OS << " ";
824     
825     if (T->getQualifier())
826       T->getQualifier()->print(OS, Policy);    
827     OS << T->getIdentifier()->getName();
828     OS << TemplateSpecializationType::PrintTemplateArgumentList(
829                                                             T->getArgs(),
830                                                             T->getNumArgs(),
831                                                             Policy);
832   }
833   
834   if (S.empty())
835     S.swap(MyString);
836   else
837     S = MyString + ' ' + S;
838 }
839
840 void TypePrinter::printPackExpansion(const PackExpansionType *T, 
841                                      std::string &S) {
842   print(T->getPattern(), S);
843   S += "...";
844 }
845
846 void TypePrinter::printAttributed(const AttributedType *T,
847                                   std::string &S) {
848   // Prefer the macro forms of the GC and ownership qualifiers.
849   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
850       T->getAttrKind() == AttributedType::attr_objc_ownership)
851     return print(T->getEquivalentType(), S);
852
853   print(T->getModifiedType(), S);
854
855   // TODO: not all attributes are GCC-style attributes.
856   S += " __attribute__((";
857   switch (T->getAttrKind()) {
858   case AttributedType::attr_address_space:
859     S += "address_space(";
860     S += T->getEquivalentType().getAddressSpace();
861     S += ")";
862     break;
863
864   case AttributedType::attr_vector_size: {
865     S += "__vector_size__(";
866     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
867       S += vector->getNumElements();
868       S += " * sizeof(";
869
870       std::string tmp;
871       print(vector->getElementType(), tmp);
872       S += tmp;
873       S += ")";
874     }
875     S += ")";
876     break;
877   }
878
879   case AttributedType::attr_neon_vector_type:
880   case AttributedType::attr_neon_polyvector_type: {
881     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
882       S += "neon_vector_type(";
883     else
884       S += "neon_polyvector_type(";
885     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
886     S += llvm::utostr_32(vector->getNumElements());
887     S += ")";
888     break;
889   }
890
891   case AttributedType::attr_regparm: {
892     S += "regparm(";
893     QualType t = T->getEquivalentType();
894     while (!t->isFunctionType())
895       t = t->getPointeeType();
896     S += t->getAs<FunctionType>()->getRegParmType();
897     S += ")";
898     break;
899   }
900
901   case AttributedType::attr_objc_gc: {
902     S += "objc_gc(";
903
904     QualType tmp = T->getEquivalentType();
905     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
906       QualType next = tmp->getPointeeType();
907       if (next == tmp) break;
908       tmp = next;
909     }
910
911     if (tmp.isObjCGCWeak())
912       S += "weak";
913     else
914       S += "strong";
915     S += ")";
916     break;
917   }
918
919   case AttributedType::attr_objc_ownership:
920     S += "objc_ownership(";
921     switch (T->getEquivalentType().getObjCLifetime()) {
922     case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
923     case Qualifiers::OCL_ExplicitNone: S += "none"; break;
924     case Qualifiers::OCL_Strong: S += "strong"; break;
925     case Qualifiers::OCL_Weak: S += "weak"; break;
926     case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
927     }
928     S += ")";
929     break;
930
931   case AttributedType::attr_noreturn: S += "noreturn"; break;
932   case AttributedType::attr_cdecl: S += "cdecl"; break;
933   case AttributedType::attr_fastcall: S += "fastcall"; break;
934   case AttributedType::attr_stdcall: S += "stdcall"; break;
935   case AttributedType::attr_thiscall: S += "thiscall"; break;
936   case AttributedType::attr_pascal: S += "pascal"; break;
937   case AttributedType::attr_pcs: {
938    S += "pcs(";
939    QualType t = T->getEquivalentType();
940    while (!t->isFunctionType())
941      t = t->getPointeeType();
942    S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
943          "\"aapcs\"" : "\"aapcs-vfp\"");
944    S += ")";
945    break;
946   }
947   }
948   S += "))";
949 }
950
951 void TypePrinter::printObjCInterface(const ObjCInterfaceType *T, 
952                                      std::string &S) { 
953   if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
954     S = ' ' + S;
955
956   std::string ObjCQIString = T->getDecl()->getNameAsString();
957   S = ObjCQIString + S;
958 }
959
960 void TypePrinter::printObjCObject(const ObjCObjectType *T,
961                                   std::string &S) {
962   if (T->qual_empty())
963     return print(T->getBaseType(), S);
964
965   std::string tmp;
966   print(T->getBaseType(), tmp);
967   tmp += '<';
968   bool isFirst = true;
969   for (ObjCObjectType::qual_iterator
970          I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
971     if (isFirst)
972       isFirst = false;
973     else
974       tmp += ',';
975     tmp += (*I)->getNameAsString();
976   }
977   tmp += '>';
978
979   if (!S.empty()) {
980     tmp += ' ';
981     tmp += S;
982   }
983   std::swap(tmp, S);
984 }
985
986 void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T, 
987                                          std::string &S) { 
988   std::string ObjCQIString;
989   
990   T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString, 
991                                                                Policy);
992   if (!ObjCQIString.empty())
993     ObjCQIString += ' ';
994     
995   if (T->isObjCIdType() || T->isObjCQualifiedIdType())
996     ObjCQIString += "id";
997   else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
998     ObjCQIString += "Class";
999   else if (T->isObjCSelType())
1000     ObjCQIString += "SEL";
1001   else
1002     ObjCQIString += T->getInterfaceDecl()->getNameAsString();
1003   
1004   if (!T->qual_empty()) {
1005     ObjCQIString += '<';
1006     for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(), 
1007                                               E = T->qual_end();
1008          I != E; ++I) {
1009       ObjCQIString += (*I)->getNameAsString();
1010       if (I+1 != E)
1011         ObjCQIString += ',';
1012     }
1013     ObjCQIString += '>';
1014   }
1015   
1016   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
1017     ObjCQIString += " *"; // Don't forget the implicit pointer.
1018   else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1019     S = ' ' + S;
1020   
1021   S = ObjCQIString + S;  
1022 }
1023
1024 std::string TemplateSpecializationType::
1025   PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
1026                             const PrintingPolicy &Policy) {
1027   return PrintTemplateArgumentList(Args.getArgumentArray(),
1028                                    Args.size(),
1029                                    Policy);
1030 }
1031
1032 std::string
1033 TemplateSpecializationType::PrintTemplateArgumentList(
1034                                                 const TemplateArgument *Args,
1035                                                 unsigned NumArgs,
1036                                                   const PrintingPolicy &Policy,
1037                                                       bool SkipBrackets) {
1038   std::string SpecString;
1039   if (!SkipBrackets)
1040     SpecString += '<';
1041   
1042   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1043     if (SpecString.size() > unsigned(!SkipBrackets))
1044       SpecString += ", ";
1045     
1046     // Print the argument into a string.
1047     std::string ArgString;
1048     if (Args[Arg].getKind() == TemplateArgument::Pack) {
1049       ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(), 
1050                                             Args[Arg].pack_size(), 
1051                                             Policy, true);
1052     } else {
1053       llvm::raw_string_ostream ArgOut(ArgString);
1054       Args[Arg].print(Policy, ArgOut);
1055     }
1056    
1057     // If this is the first argument and its string representation
1058     // begins with the global scope specifier ('::foo'), add a space
1059     // to avoid printing the diagraph '<:'.
1060     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1061       SpecString += ' ';
1062     
1063     SpecString += ArgString;
1064   }
1065   
1066   // If the last character of our string is '>', add another space to
1067   // keep the two '>''s separate tokens. We don't *have* to do this in
1068   // C++0x, but it's still good hygiene.
1069   if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
1070     SpecString += ' ';
1071   
1072   if (!SkipBrackets)
1073     SpecString += '>';
1074   
1075   return SpecString;
1076 }
1077
1078 // Sadly, repeat all that with TemplateArgLoc.
1079 std::string TemplateSpecializationType::
1080 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1081                           const PrintingPolicy &Policy) {
1082   std::string SpecString;
1083   SpecString += '<';
1084   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1085     if (SpecString.size() > 1)
1086       SpecString += ", ";
1087     
1088     // Print the argument into a string.
1089     std::string ArgString;
1090     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1091       ArgString = PrintTemplateArgumentList(
1092                                            Args[Arg].getArgument().pack_begin(), 
1093                                             Args[Arg].getArgument().pack_size(), 
1094                                             Policy, true);
1095     } else {
1096       llvm::raw_string_ostream ArgOut(ArgString);
1097       Args[Arg].getArgument().print(Policy, ArgOut);
1098     }
1099     
1100     // If this is the first argument and its string representation
1101     // begins with the global scope specifier ('::foo'), add a space
1102     // to avoid printing the diagraph '<:'.
1103     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1104       SpecString += ' ';
1105     
1106     SpecString += ArgString;
1107   }
1108   
1109   // If the last character of our string is '>', add another space to
1110   // keep the two '>''s separate tokens. We don't *have* to do this in
1111   // C++0x, but it's still good hygiene.
1112   if (SpecString[SpecString.size() - 1] == '>')
1113     SpecString += ' ';
1114   
1115   SpecString += '>';
1116   
1117   return SpecString;
1118 }
1119
1120 void QualType::dump(const char *msg) const {
1121   std::string R = "identifier";
1122   LangOptions LO;
1123   getAsStringInternal(R, PrintingPolicy(LO));
1124   if (msg)
1125     llvm::errs() << msg << ": ";
1126   llvm::errs() << R << "\n";
1127 }
1128 void QualType::dump() const {
1129   dump("");
1130 }
1131
1132 void Type::dump() const {
1133   QualType(this, 0).dump();
1134 }
1135
1136 std::string Qualifiers::getAsString() const {
1137   LangOptions LO;
1138   return getAsString(PrintingPolicy(LO));
1139 }
1140
1141 // Appends qualifiers to the given string, separated by spaces.  Will
1142 // prefix a space if the string is non-empty.  Will not append a final
1143 // space.
1144 void Qualifiers::getAsStringInternal(std::string &S,
1145                                      const PrintingPolicy& Policy) const {
1146   AppendTypeQualList(S, getCVRQualifiers());
1147   if (unsigned addrspace = getAddressSpace()) {
1148     if (!S.empty()) S += ' ';
1149     S += "__attribute__((address_space(";
1150     S += llvm::utostr_32(addrspace);
1151     S += ")))";
1152   }
1153   if (Qualifiers::GC gc = getObjCGCAttr()) {
1154     if (!S.empty()) S += ' ';
1155     if (gc == Qualifiers::Weak)
1156       S += "__weak";
1157     else
1158       S += "__strong";
1159   }
1160   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1161     if (!S.empty() && 
1162         !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1163       S += ' ';
1164     
1165     switch (lifetime) {
1166     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1167     case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
1168     case Qualifiers::OCL_Strong: 
1169       if (!Policy.SuppressStrongLifetime)
1170         S += "__strong"; 
1171       break;
1172         
1173     case Qualifiers::OCL_Weak: S += "__weak"; break;
1174     case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
1175     }
1176   }
1177 }
1178
1179 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1180   std::string buffer;
1181   LangOptions options;
1182   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1183   return buffer;
1184 }
1185
1186 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1187                                    std::string &buffer,
1188                                    const PrintingPolicy &policy) {
1189   TypePrinter(policy).print(ty, qs, buffer);
1190 }