TypePrinter.cpp revision 01d08018b7cf5ce1601707cfd7a84d22015fc04e
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"
24using namespace clang;
25
26namespace {
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
61static 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
76void TypePrinter::print(QualType t, std::string &buffer) {
77  SplitQualType split = t.split();
78  print(split.first, split.second, buffer);
79}
80
81void 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
207void 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
217void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
218  print(T->getElementType(), S);
219  S = "_Complex " + S;
220}
221
222void 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
234void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
235  S = '^' + S;
236  print(T->getPointeeType(), S);
237}
238
239void 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
252void 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
265void 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
281void 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
291void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
292                                       std::string &S) {
293  S += "[]";
294  IncludeStrongLifetimeRAII Strong(Policy);
295  print(T->getElementType(), S);
296}
297
298void 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
324void 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
340void 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
355void 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
393void 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
400void
401FunctionProtoType::printExceptionSpecification(std::string &S,
402                                               PrintingPolicy Policy) const {
403
404  if (hasDynamicExceptionSpec()) {
405    S += " throw(";
406    if (getExceptionSpecType() == EST_MSAny)
407      S += "...";
408    else
409      for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
410        if (I)
411          S += ", ";
412
413        S += getExceptionType(I).getAsString(Policy);
414      }
415    S += ")";
416  } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
417    S += " noexcept";
418    if (getExceptionSpecType() == EST_ComputedNoexcept) {
419      S += "(";
420      llvm::raw_string_ostream EOut(S);
421      getNoexceptExpr()->printPretty(EOut, 0, Policy);
422      EOut.flush();
423      S += EOut.str();
424      S += ")";
425    }
426  }
427}
428
429void TypePrinter::printFunctionProto(const FunctionProtoType *T,
430                                     std::string &S) {
431  // If needed for precedence reasons, wrap the inner part in grouping parens.
432  if (!S.empty())
433    S = "(" + S + ")";
434
435  S += "(";
436  std::string Tmp;
437  PrintingPolicy ParamPolicy(Policy);
438  ParamPolicy.SuppressSpecifiers = false;
439  for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
440    if (i) S += ", ";
441    print(T->getArgType(i), Tmp);
442    S += Tmp;
443    Tmp.clear();
444  }
445
446  if (T->isVariadic()) {
447    if (T->getNumArgs())
448      S += ", ";
449    S += "...";
450  } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
451    // Do not emit int() if we have a proto, emit 'int(void)'.
452    S += "void";
453  }
454
455  S += ")";
456
457  FunctionType::ExtInfo Info = T->getExtInfo();
458  switch(Info.getCC()) {
459  case CC_Default: break;
460  case CC_C:
461    S += " __attribute__((cdecl))";
462    break;
463  case CC_X86StdCall:
464    S += " __attribute__((stdcall))";
465    break;
466  case CC_X86FastCall:
467    S += " __attribute__((fastcall))";
468    break;
469  case CC_X86ThisCall:
470    S += " __attribute__((thiscall))";
471    break;
472  case CC_X86Pascal:
473    S += " __attribute__((pascal))";
474    break;
475  case CC_AAPCS:
476    S += " __attribute__((pcs(\"aapcs\")))";
477    break;
478  case CC_AAPCS_VFP:
479    S += " __attribute__((pcs(\"aapcs-vfp\")))";
480    break;
481  }
482  if (Info.getNoReturn())
483    S += " __attribute__((noreturn))";
484  if (Info.getRegParm())
485    S += " __attribute__((regparm (" +
486        llvm::utostr_32(Info.getRegParm()) + ")))";
487
488  AppendTypeQualList(S, T->getTypeQuals());
489
490  switch (T->getRefQualifier()) {
491  case RQ_None:
492    break;
493
494  case RQ_LValue:
495    S += " &";
496    break;
497
498  case RQ_RValue:
499    S += " &&";
500    break;
501  }
502  T->printExceptionSpecification(S, Policy);
503  print(T->getResultType(), S);
504}
505
506void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
507                                       std::string &S) {
508  // If needed for precedence reasons, wrap the inner part in grouping parens.
509  if (!S.empty())
510    S = "(" + S + ")";
511
512  S += "()";
513  if (T->getNoReturnAttr())
514    S += " __attribute__((noreturn))";
515  print(T->getResultType(), S);
516}
517
518static void printTypeSpec(const NamedDecl *D, std::string &S) {
519  IdentifierInfo *II = D->getIdentifier();
520  if (S.empty())
521    S = II->getName().str();
522  else
523    S = II->getName().str() + ' ' + S;
524}
525
526void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
527                                       std::string &S) {
528  printTypeSpec(T->getDecl(), S);
529}
530
531void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
532  printTypeSpec(T->getDecl(), S);
533}
534
535void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
536  if (!S.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
537    S = ' ' + S;
538  std::string Str;
539  llvm::raw_string_ostream s(Str);
540  T->getUnderlyingExpr()->printPretty(s, 0, Policy);
541  S = "typeof " + s.str() + S;
542}
543
544void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
545  if (!S.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
546    S = ' ' + S;
547  std::string Tmp;
548  print(T->getUnderlyingType(), Tmp);
549  S = "typeof(" + Tmp + ")" + S;
550}
551
552void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
553  if (!S.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
554    S = ' ' + S;
555  std::string Str;
556  llvm::raw_string_ostream s(Str);
557  T->getUnderlyingExpr()->printPretty(s, 0, Policy);
558  S = "decltype(" + s.str() + ")" + S;
559}
560
561void TypePrinter::printUnaryTransform(const UnaryTransformType *T,
562                                           std::string &S) {
563  if (!S.empty())
564    S = ' ' + S;
565  std::string Str;
566  IncludeStrongLifetimeRAII Strong(Policy);
567  print(T->getBaseType(), Str);
568
569  switch (T->getUTTKind()) {
570    case UnaryTransformType::EnumUnderlyingType:
571      S = "__underlying_type(" + Str + ")" + S;
572      break;
573  }
574}
575
576void TypePrinter::printAuto(const AutoType *T, std::string &S) {
577  // If the type has been deduced, do not print 'auto'.
578  if (T->isDeduced()) {
579    print(T->getDeducedType(), S);
580  } else {
581    if (!S.empty())    // Prefix the basic type, e.g. 'auto X'.
582      S = ' ' + S;
583    S = "auto" + S;
584  }
585}
586
587void TypePrinter::printAtomic(const AtomicType *T, std::string &S) {
588  if (!S.empty())
589    S = ' ' + S;
590  std::string Str;
591  IncludeStrongLifetimeRAII Strong(Policy);
592  print(T->getValueType(), Str);
593
594  S = "_Atomic(" + Str + ")" + S;
595}
596
597/// Appends the given scope to the end of a string.
598void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
599  if (DC->isTranslationUnit()) return;
600  AppendScope(DC->getParent(), Buffer);
601
602  unsigned OldSize = Buffer.size();
603
604  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
605    if (Policy.SuppressUnwrittenScope &&
606        (NS->isAnonymousNamespace() || NS->isInline()))
607      return;
608    if (NS->getIdentifier())
609      Buffer += NS->getNameAsString();
610    else
611      Buffer += "<anonymous>";
612  } else if (ClassTemplateSpecializationDecl *Spec
613               = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
614    IncludeStrongLifetimeRAII Strong(Policy);
615    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
616    std::string TemplateArgsStr
617      = TemplateSpecializationType::PrintTemplateArgumentList(
618                                            TemplateArgs.data(),
619                                            TemplateArgs.size(),
620                                            Policy);
621    Buffer += Spec->getIdentifier()->getName();
622    Buffer += TemplateArgsStr;
623  } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
624    if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
625      Buffer += Typedef->getIdentifier()->getName();
626    else if (Tag->getIdentifier())
627      Buffer += Tag->getIdentifier()->getName();
628    else
629      return;
630  }
631
632  if (Buffer.size() != OldSize)
633    Buffer += "::";
634}
635
636void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
637  if (Policy.SuppressTag)
638    return;
639
640  std::string Buffer;
641  bool HasKindDecoration = false;
642
643  // bool SuppressTagKeyword
644  //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
645
646  // We don't print tags unless this is an elaborated type.
647  // In C, we just assume every RecordType is an elaborated type.
648  if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
649        D->getTypedefNameForAnonDecl())) {
650    HasKindDecoration = true;
651    Buffer += D->getKindName();
652    Buffer += ' ';
653  }
654
655  // Compute the full nested-name-specifier for this type.
656  // In C, this will always be empty except when the type
657  // being printed is anonymous within other Record.
658  if (!Policy.SuppressScope)
659    AppendScope(D->getDeclContext(), Buffer);
660
661  if (const IdentifierInfo *II = D->getIdentifier())
662    Buffer += II->getNameStart();
663  else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
664    assert(Typedef->getIdentifier() && "Typedef without identifier?");
665    Buffer += Typedef->getIdentifier()->getNameStart();
666  } else {
667    // Make an unambiguous representation for anonymous types, e.g.
668    //   <anonymous enum at /usr/include/string.h:120:9>
669    llvm::raw_string_ostream OS(Buffer);
670    OS << "<anonymous";
671
672    if (Policy.AnonymousTagLocations) {
673      // Suppress the redundant tag keyword if we just printed one.
674      // We don't have to worry about ElaboratedTypes here because you can't
675      // refer to an anonymous type with one.
676      if (!HasKindDecoration)
677        OS << " " << D->getKindName();
678
679      PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
680          D->getLocation());
681      if (PLoc.isValid()) {
682        OS << " at " << PLoc.getFilename()
683           << ':' << PLoc.getLine()
684           << ':' << PLoc.getColumn();
685      }
686    }
687
688    OS << '>';
689  }
690
691  // If this is a class template specialization, print the template
692  // arguments.
693  if (ClassTemplateSpecializationDecl *Spec
694        = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
695    const TemplateArgument *Args;
696    unsigned NumArgs;
697    if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
698      const TemplateSpecializationType *TST =
699        cast<TemplateSpecializationType>(TAW->getType());
700      Args = TST->getArgs();
701      NumArgs = TST->getNumArgs();
702    } else {
703      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
704      Args = TemplateArgs.data();
705      NumArgs = TemplateArgs.size();
706    }
707    IncludeStrongLifetimeRAII Strong(Policy);
708    Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
709                                                                    NumArgs,
710                                                                    Policy);
711  }
712
713  if (!InnerString.empty()) {
714    Buffer += ' ';
715    Buffer += InnerString;
716  }
717
718  std::swap(Buffer, InnerString);
719}
720
721void TypePrinter::printRecord(const RecordType *T, std::string &S) {
722  printTag(T->getDecl(), S);
723}
724
725void TypePrinter::printEnum(const EnumType *T, std::string &S) {
726  printTag(T->getDecl(), S);
727}
728
729void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
730                                        std::string &S) {
731  if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
732    S = ' ' + S;
733
734  if (IdentifierInfo *Id = T->getIdentifier())
735    S = Id->getName().str() + S;
736  else
737    S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
738        llvm::utostr_32(T->getIndex()) + S;
739}
740
741void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
742                                             std::string &S) {
743  IncludeStrongLifetimeRAII Strong(Policy);
744  print(T->getReplacementType(), S);
745}
746
747void TypePrinter::printSubstTemplateTypeParmPack(
748                                        const SubstTemplateTypeParmPackType *T,
749                                             std::string &S) {
750  IncludeStrongLifetimeRAII Strong(Policy);
751  printTemplateTypeParm(T->getReplacedParameter(), S);
752}
753
754void TypePrinter::printTemplateSpecialization(
755                                            const TemplateSpecializationType *T,
756                                              std::string &S) {
757  IncludeStrongLifetimeRAII Strong(Policy);
758  std::string SpecString;
759
760  {
761    llvm::raw_string_ostream OS(SpecString);
762    T->getTemplateName().print(OS, Policy);
763  }
764
765  SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
766                                                                  T->getArgs(),
767                                                                T->getNumArgs(),
768                                                                      Policy);
769  if (S.empty())
770    S.swap(SpecString);
771  else
772    S = SpecString + ' ' + S;
773}
774
775void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
776                                         std::string &S) {
777  printTemplateSpecialization(T->getInjectedTST(), S);
778}
779
780void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
781  std::string MyString;
782
783  {
784    llvm::raw_string_ostream OS(MyString);
785    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
786    if (T->getKeyword() != ETK_None)
787      OS << " ";
788    NestedNameSpecifier* Qualifier = T->getQualifier();
789    if (Qualifier)
790      Qualifier->print(OS, Policy);
791  }
792
793  std::string TypeStr;
794  PrintingPolicy InnerPolicy(Policy);
795  InnerPolicy.SuppressTagKeyword = true;
796  InnerPolicy.SuppressScope = true;
797  TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
798
799  MyString += TypeStr;
800  if (S.empty())
801    S.swap(MyString);
802  else
803    S = MyString + ' ' + S;
804}
805
806void TypePrinter::printParen(const ParenType *T, std::string &S) {
807  if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
808    S = '(' + S + ')';
809  print(T->getInnerType(), S);
810}
811
812void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
813  std::string MyString;
814
815  {
816    llvm::raw_string_ostream OS(MyString);
817    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
818    if (T->getKeyword() != ETK_None)
819      OS << " ";
820
821    T->getQualifier()->print(OS, Policy);
822
823    OS << T->getIdentifier()->getName();
824  }
825
826  if (S.empty())
827    S.swap(MyString);
828  else
829    S = MyString + ' ' + S;
830}
831
832void TypePrinter::printDependentTemplateSpecialization(
833        const DependentTemplateSpecializationType *T, std::string &S) {
834  IncludeStrongLifetimeRAII Strong(Policy);
835  std::string MyString;
836  {
837    llvm::raw_string_ostream OS(MyString);
838
839    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
840    if (T->getKeyword() != ETK_None)
841      OS << " ";
842
843    if (T->getQualifier())
844      T->getQualifier()->print(OS, Policy);
845    OS << T->getIdentifier()->getName();
846    OS << TemplateSpecializationType::PrintTemplateArgumentList(
847                                                            T->getArgs(),
848                                                            T->getNumArgs(),
849                                                            Policy);
850  }
851
852  if (S.empty())
853    S.swap(MyString);
854  else
855    S = MyString + ' ' + S;
856}
857
858void TypePrinter::printPackExpansion(const PackExpansionType *T,
859                                     std::string &S) {
860  print(T->getPattern(), S);
861  S += "...";
862}
863
864void TypePrinter::printAttributed(const AttributedType *T,
865                                  std::string &S) {
866  // Prefer the macro forms of the GC and ownership qualifiers.
867  if (T->getAttrKind() == AttributedType::attr_objc_gc ||
868      T->getAttrKind() == AttributedType::attr_objc_ownership)
869    return print(T->getEquivalentType(), S);
870
871  print(T->getModifiedType(), S);
872
873  // TODO: not all attributes are GCC-style attributes.
874  S += " __attribute__((";
875  switch (T->getAttrKind()) {
876  case AttributedType::attr_address_space:
877    S += "address_space(";
878    S += T->getEquivalentType().getAddressSpace();
879    S += ")";
880    break;
881
882  case AttributedType::attr_vector_size: {
883    S += "__vector_size__(";
884    if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
885      S += vector->getNumElements();
886      S += " * sizeof(";
887
888      std::string tmp;
889      print(vector->getElementType(), tmp);
890      S += tmp;
891      S += ")";
892    }
893    S += ")";
894    break;
895  }
896
897  case AttributedType::attr_neon_vector_type:
898  case AttributedType::attr_neon_polyvector_type: {
899    if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
900      S += "neon_vector_type(";
901    else
902      S += "neon_polyvector_type(";
903    const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
904    S += llvm::utostr_32(vector->getNumElements());
905    S += ")";
906    break;
907  }
908
909  case AttributedType::attr_regparm: {
910    S += "regparm(";
911    QualType t = T->getEquivalentType();
912    while (!t->isFunctionType())
913      t = t->getPointeeType();
914    S += t->getAs<FunctionType>()->getRegParmType();
915    S += ")";
916    break;
917  }
918
919  case AttributedType::attr_objc_gc: {
920    S += "objc_gc(";
921
922    QualType tmp = T->getEquivalentType();
923    while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
924      QualType next = tmp->getPointeeType();
925      if (next == tmp) break;
926      tmp = next;
927    }
928
929    if (tmp.isObjCGCWeak())
930      S += "weak";
931    else
932      S += "strong";
933    S += ")";
934    break;
935  }
936
937  case AttributedType::attr_objc_ownership:
938    S += "objc_ownership(";
939    switch (T->getEquivalentType().getObjCLifetime()) {
940    case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
941    case Qualifiers::OCL_ExplicitNone: S += "none"; break;
942    case Qualifiers::OCL_Strong: S += "strong"; break;
943    case Qualifiers::OCL_Weak: S += "weak"; break;
944    case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
945    }
946    S += ")";
947    break;
948
949  case AttributedType::attr_noreturn: S += "noreturn"; break;
950  case AttributedType::attr_cdecl: S += "cdecl"; break;
951  case AttributedType::attr_fastcall: S += "fastcall"; break;
952  case AttributedType::attr_stdcall: S += "stdcall"; break;
953  case AttributedType::attr_thiscall: S += "thiscall"; break;
954  case AttributedType::attr_pascal: S += "pascal"; break;
955  case AttributedType::attr_pcs: {
956   S += "pcs(";
957   QualType t = T->getEquivalentType();
958   while (!t->isFunctionType())
959     t = t->getPointeeType();
960   S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
961         "\"aapcs\"" : "\"aapcs-vfp\"");
962   S += ")";
963   break;
964  }
965  }
966  S += "))";
967}
968
969void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
970                                     std::string &S) {
971  if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
972    S = ' ' + S;
973
974  std::string ObjCQIString = T->getDecl()->getNameAsString();
975  S = ObjCQIString + S;
976}
977
978void TypePrinter::printObjCObject(const ObjCObjectType *T,
979                                  std::string &S) {
980  if (T->qual_empty())
981    return print(T->getBaseType(), S);
982
983  std::string tmp;
984  print(T->getBaseType(), tmp);
985  tmp += '<';
986  bool isFirst = true;
987  for (ObjCObjectType::qual_iterator
988         I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
989    if (isFirst)
990      isFirst = false;
991    else
992      tmp += ',';
993    tmp += (*I)->getNameAsString();
994  }
995  tmp += '>';
996
997  if (!S.empty()) {
998    tmp += ' ';
999    tmp += S;
1000  }
1001  std::swap(tmp, S);
1002}
1003
1004void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
1005                                         std::string &S) {
1006  std::string ObjCQIString;
1007
1008  T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
1009                                                               Policy);
1010  if (!ObjCQIString.empty())
1011    ObjCQIString += ' ';
1012
1013  if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1014    ObjCQIString += "id";
1015  else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1016    ObjCQIString += "Class";
1017  else if (T->isObjCSelType())
1018    ObjCQIString += "SEL";
1019  else
1020    ObjCQIString += T->getInterfaceDecl()->getNameAsString();
1021
1022  if (!T->qual_empty()) {
1023    ObjCQIString += '<';
1024    for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1025                                              E = T->qual_end();
1026         I != E; ++I) {
1027      ObjCQIString += (*I)->getNameAsString();
1028      if (I+1 != E)
1029        ObjCQIString += ',';
1030    }
1031    ObjCQIString += '>';
1032  }
1033
1034  if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
1035    ObjCQIString += " *"; // Don't forget the implicit pointer.
1036  else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1037    S = ' ' + S;
1038
1039  S = ObjCQIString + S;
1040}
1041
1042std::string TemplateSpecializationType::
1043  PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
1044                            const PrintingPolicy &Policy) {
1045  return PrintTemplateArgumentList(Args.getArgumentArray(),
1046                                   Args.size(),
1047                                   Policy);
1048}
1049
1050std::string
1051TemplateSpecializationType::PrintTemplateArgumentList(
1052                                                const TemplateArgument *Args,
1053                                                unsigned NumArgs,
1054                                                  const PrintingPolicy &Policy,
1055                                                      bool SkipBrackets) {
1056  std::string SpecString;
1057  if (!SkipBrackets)
1058    SpecString += '<';
1059
1060  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1061    if (SpecString.size() > unsigned(!SkipBrackets))
1062      SpecString += ", ";
1063
1064    // Print the argument into a string.
1065    std::string ArgString;
1066    if (Args[Arg].getKind() == TemplateArgument::Pack) {
1067      ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
1068                                            Args[Arg].pack_size(),
1069                                            Policy, true);
1070    } else {
1071      llvm::raw_string_ostream ArgOut(ArgString);
1072      Args[Arg].print(Policy, ArgOut);
1073    }
1074
1075    // If this is the first argument and its string representation
1076    // begins with the global scope specifier ('::foo'), add a space
1077    // to avoid printing the diagraph '<:'.
1078    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1079      SpecString += ' ';
1080
1081    SpecString += ArgString;
1082  }
1083
1084  // If the last character of our string is '>', add another space to
1085  // keep the two '>''s separate tokens. We don't *have* to do this in
1086  // C++0x, but it's still good hygiene.
1087  if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
1088    SpecString += ' ';
1089
1090  if (!SkipBrackets)
1091    SpecString += '>';
1092
1093  return SpecString;
1094}
1095
1096// Sadly, repeat all that with TemplateArgLoc.
1097std::string TemplateSpecializationType::
1098PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1099                          const PrintingPolicy &Policy) {
1100  std::string SpecString;
1101  SpecString += '<';
1102  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1103    if (SpecString.size() > 1)
1104      SpecString += ", ";
1105
1106    // Print the argument into a string.
1107    std::string ArgString;
1108    if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1109      ArgString = PrintTemplateArgumentList(
1110                                           Args[Arg].getArgument().pack_begin(),
1111                                            Args[Arg].getArgument().pack_size(),
1112                                            Policy, true);
1113    } else {
1114      llvm::raw_string_ostream ArgOut(ArgString);
1115      Args[Arg].getArgument().print(Policy, ArgOut);
1116    }
1117
1118    // If this is the first argument and its string representation
1119    // begins with the global scope specifier ('::foo'), add a space
1120    // to avoid printing the diagraph '<:'.
1121    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1122      SpecString += ' ';
1123
1124    SpecString += ArgString;
1125  }
1126
1127  // If the last character of our string is '>', add another space to
1128  // keep the two '>''s separate tokens. We don't *have* to do this in
1129  // C++0x, but it's still good hygiene.
1130  if (SpecString[SpecString.size() - 1] == '>')
1131    SpecString += ' ';
1132
1133  SpecString += '>';
1134
1135  return SpecString;
1136}
1137
1138void QualType::dump(const char *msg) const {
1139  std::string R = "identifier";
1140  LangOptions LO;
1141  getAsStringInternal(R, PrintingPolicy(LO));
1142  if (msg)
1143    llvm::errs() << msg << ": ";
1144  llvm::errs() << R << "\n";
1145}
1146void QualType::dump() const {
1147  dump("");
1148}
1149
1150void Type::dump() const {
1151  QualType(this, 0).dump();
1152}
1153
1154std::string Qualifiers::getAsString() const {
1155  LangOptions LO;
1156  return getAsString(PrintingPolicy(LO));
1157}
1158
1159// Appends qualifiers to the given string, separated by spaces.  Will
1160// prefix a space if the string is non-empty.  Will not append a final
1161// space.
1162void Qualifiers::getAsStringInternal(std::string &S,
1163                                     const PrintingPolicy& Policy) const {
1164  AppendTypeQualList(S, getCVRQualifiers());
1165  if (unsigned addrspace = getAddressSpace()) {
1166    if (!S.empty()) S += ' ';
1167    switch (addrspace) {
1168      case LangAS::opencl_global:
1169        S += "__global";
1170        break;
1171      case LangAS::opencl_local:
1172        S += "__local";
1173        break;
1174      case LangAS::opencl_constant:
1175        S += "__constant";
1176        break;
1177      default:
1178        S += "__attribute__((address_space(";
1179        S += llvm::utostr_32(addrspace);
1180        S += ")))";
1181    }
1182  }
1183  if (Qualifiers::GC gc = getObjCGCAttr()) {
1184    if (!S.empty()) S += ' ';
1185    if (gc == Qualifiers::Weak)
1186      S += "__weak";
1187    else
1188      S += "__strong";
1189  }
1190  if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1191    if (!S.empty() &&
1192        !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1193      S += ' ';
1194
1195    switch (lifetime) {
1196    case Qualifiers::OCL_None: llvm_unreachable("none but true");
1197    case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
1198    case Qualifiers::OCL_Strong:
1199      if (!Policy.SuppressStrongLifetime)
1200        S += "__strong";
1201      break;
1202
1203    case Qualifiers::OCL_Weak: S += "__weak"; break;
1204    case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
1205    }
1206  }
1207}
1208
1209std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1210  std::string buffer;
1211  LangOptions options;
1212  getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1213  return buffer;
1214}
1215
1216void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1217                                   std::string &buffer,
1218                                   const PrintingPolicy &policy) {
1219  TypePrinter(policy).print(ty, qs, buffer);
1220}
1221