TypePrinter.cpp revision 321369
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/PrettyPrinter.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/SaveAndRestore.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace clang;
28
29namespace {
30  /// \brief RAII object that enables printing of the ARC __strong lifetime
31  /// qualifier.
32  class IncludeStrongLifetimeRAII {
33    PrintingPolicy &Policy;
34    bool Old;
35
36  public:
37    explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
38      : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
39        if (!Policy.SuppressLifetimeQualifiers)
40          Policy.SuppressStrongLifetime = false;
41    }
42
43    ~IncludeStrongLifetimeRAII() {
44      Policy.SuppressStrongLifetime = Old;
45    }
46  };
47
48  class ParamPolicyRAII {
49    PrintingPolicy &Policy;
50    bool Old;
51
52  public:
53    explicit ParamPolicyRAII(PrintingPolicy &Policy)
54      : Policy(Policy), Old(Policy.SuppressSpecifiers) {
55      Policy.SuppressSpecifiers = false;
56    }
57
58    ~ParamPolicyRAII() {
59      Policy.SuppressSpecifiers = Old;
60    }
61  };
62
63  class ElaboratedTypePolicyRAII {
64    PrintingPolicy &Policy;
65    bool SuppressTagKeyword;
66    bool SuppressScope;
67
68  public:
69    explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
70      SuppressTagKeyword = Policy.SuppressTagKeyword;
71      SuppressScope = Policy.SuppressScope;
72      Policy.SuppressTagKeyword = true;
73      Policy.SuppressScope = true;
74    }
75
76    ~ElaboratedTypePolicyRAII() {
77      Policy.SuppressTagKeyword = SuppressTagKeyword;
78      Policy.SuppressScope = SuppressScope;
79    }
80  };
81
82  class TypePrinter {
83    PrintingPolicy Policy;
84    unsigned Indentation;
85    bool HasEmptyPlaceHolder;
86    bool InsideCCAttribute;
87
88  public:
89    explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
90      : Policy(Policy), Indentation(Indentation),
91        HasEmptyPlaceHolder(false), InsideCCAttribute(false) { }
92
93    void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
94               StringRef PlaceHolder);
95    void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
96
97    static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
98    void spaceBeforePlaceHolder(raw_ostream &OS);
99    void printTypeSpec(NamedDecl *D, raw_ostream &OS);
100
101    void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
102    void printBefore(QualType T, raw_ostream &OS);
103    void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
104    void printAfter(QualType T, raw_ostream &OS);
105    void AppendScope(DeclContext *DC, raw_ostream &OS);
106    void printTag(TagDecl *T, raw_ostream &OS);
107    void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
108#define ABSTRACT_TYPE(CLASS, PARENT)
109#define TYPE(CLASS, PARENT) \
110    void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
111    void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
112#include "clang/AST/TypeNodes.def"
113  };
114}
115
116static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
117                               bool HasRestrictKeyword) {
118  bool appendSpace = false;
119  if (TypeQuals & Qualifiers::Const) {
120    OS << "const";
121    appendSpace = true;
122  }
123  if (TypeQuals & Qualifiers::Volatile) {
124    if (appendSpace) OS << ' ';
125    OS << "volatile";
126    appendSpace = true;
127  }
128  if (TypeQuals & Qualifiers::Restrict) {
129    if (appendSpace) OS << ' ';
130    if (HasRestrictKeyword) {
131      OS << "restrict";
132    } else {
133      OS << "__restrict";
134    }
135  }
136}
137
138void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
139  if (!HasEmptyPlaceHolder)
140    OS << ' ';
141}
142
143void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
144  SplitQualType split = t.split();
145  print(split.Ty, split.Quals, OS, PlaceHolder);
146}
147
148void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
149                        StringRef PlaceHolder) {
150  if (!T) {
151    OS << "NULL TYPE";
152    return;
153  }
154
155  SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
156
157  printBefore(T, Quals, OS);
158  OS << PlaceHolder;
159  printAfter(T, Quals, OS);
160}
161
162bool TypePrinter::canPrefixQualifiers(const Type *T,
163                                      bool &NeedARCStrongQualifier) {
164  // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
165  // so that we get "const int" instead of "int const", but we can't do this if
166  // the type is complex.  For example if the type is "int*", we *must* print
167  // "int * const", printing "const int *" is different.  Only do this when the
168  // type expands to a simple string.
169  bool CanPrefixQualifiers = false;
170  NeedARCStrongQualifier = false;
171  Type::TypeClass TC = T->getTypeClass();
172  if (const AutoType *AT = dyn_cast<AutoType>(T))
173    TC = AT->desugar()->getTypeClass();
174  if (const SubstTemplateTypeParmType *Subst
175                                      = dyn_cast<SubstTemplateTypeParmType>(T))
176    TC = Subst->getReplacementType()->getTypeClass();
177
178  switch (TC) {
179    case Type::Auto:
180    case Type::Builtin:
181    case Type::Complex:
182    case Type::UnresolvedUsing:
183    case Type::Typedef:
184    case Type::TypeOfExpr:
185    case Type::TypeOf:
186    case Type::Decltype:
187    case Type::UnaryTransform:
188    case Type::Record:
189    case Type::Enum:
190    case Type::Elaborated:
191    case Type::TemplateTypeParm:
192    case Type::SubstTemplateTypeParmPack:
193    case Type::DeducedTemplateSpecialization:
194    case Type::TemplateSpecialization:
195    case Type::InjectedClassName:
196    case Type::DependentName:
197    case Type::DependentTemplateSpecialization:
198    case Type::ObjCObject:
199    case Type::ObjCTypeParam:
200    case Type::ObjCInterface:
201    case Type::Atomic:
202    case Type::Pipe:
203      CanPrefixQualifiers = true;
204      break;
205
206    case Type::ObjCObjectPointer:
207      CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
208        T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
209      break;
210
211    case Type::ConstantArray:
212    case Type::IncompleteArray:
213    case Type::VariableArray:
214    case Type::DependentSizedArray:
215      NeedARCStrongQualifier = true;
216      // Fall through
217
218    case Type::Adjusted:
219    case Type::Decayed:
220    case Type::Pointer:
221    case Type::BlockPointer:
222    case Type::LValueReference:
223    case Type::RValueReference:
224    case Type::MemberPointer:
225    case Type::DependentSizedExtVector:
226    case Type::Vector:
227    case Type::ExtVector:
228    case Type::FunctionProto:
229    case Type::FunctionNoProto:
230    case Type::Paren:
231    case Type::Attributed:
232    case Type::PackExpansion:
233    case Type::SubstTemplateTypeParm:
234      CanPrefixQualifiers = false;
235      break;
236  }
237
238  return CanPrefixQualifiers;
239}
240
241void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
242  SplitQualType Split = T.split();
243
244  // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
245  // at this level.
246  Qualifiers Quals = Split.Quals;
247  if (const SubstTemplateTypeParmType *Subst =
248        dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
249    Quals -= QualType(Subst, 0).getQualifiers();
250
251  printBefore(Split.Ty, Quals, OS);
252}
253
254/// \brief Prints the part of the type string before an identifier, e.g. for
255/// "int foo[10]" it prints "int ".
256void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
257  if (Policy.SuppressSpecifiers && T->isSpecifierType())
258    return;
259
260  SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
261
262  // Print qualifiers as appropriate.
263
264  bool CanPrefixQualifiers = false;
265  bool NeedARCStrongQualifier = false;
266  CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
267
268  if (CanPrefixQualifiers && !Quals.empty()) {
269    if (NeedARCStrongQualifier) {
270      IncludeStrongLifetimeRAII Strong(Policy);
271      Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
272    } else {
273      Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
274    }
275  }
276
277  bool hasAfterQuals = false;
278  if (!CanPrefixQualifiers && !Quals.empty()) {
279    hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
280    if (hasAfterQuals)
281      HasEmptyPlaceHolder = false;
282  }
283
284  switch (T->getTypeClass()) {
285#define ABSTRACT_TYPE(CLASS, PARENT)
286#define TYPE(CLASS, PARENT) case Type::CLASS: \
287    print##CLASS##Before(cast<CLASS##Type>(T), OS); \
288    break;
289#include "clang/AST/TypeNodes.def"
290  }
291
292  if (hasAfterQuals) {
293    if (NeedARCStrongQualifier) {
294      IncludeStrongLifetimeRAII Strong(Policy);
295      Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
296    } else {
297      Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
298    }
299  }
300}
301
302void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
303  SplitQualType split = t.split();
304  printAfter(split.Ty, split.Quals, OS);
305}
306
307/// \brief Prints the part of the type string after an identifier, e.g. for
308/// "int foo[10]" it prints "[10]".
309void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
310  switch (T->getTypeClass()) {
311#define ABSTRACT_TYPE(CLASS, PARENT)
312#define TYPE(CLASS, PARENT) case Type::CLASS: \
313    print##CLASS##After(cast<CLASS##Type>(T), OS); \
314    break;
315#include "clang/AST/TypeNodes.def"
316  }
317}
318
319void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
320  OS << T->getName(Policy);
321  spaceBeforePlaceHolder(OS);
322}
323void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) { }
324
325void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
326  OS << "_Complex ";
327  printBefore(T->getElementType(), OS);
328}
329void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
330  printAfter(T->getElementType(), OS);
331}
332
333void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
334  IncludeStrongLifetimeRAII Strong(Policy);
335  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
336  printBefore(T->getPointeeType(), OS);
337  // Handle things like 'int (*A)[4];' correctly.
338  // FIXME: this should include vectors, but vectors use attributes I guess.
339  if (isa<ArrayType>(T->getPointeeType()))
340    OS << '(';
341  OS << '*';
342}
343void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
344  IncludeStrongLifetimeRAII Strong(Policy);
345  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
346  // Handle things like 'int (*A)[4];' correctly.
347  // FIXME: this should include vectors, but vectors use attributes I guess.
348  if (isa<ArrayType>(T->getPointeeType()))
349    OS << ')';
350  printAfter(T->getPointeeType(), OS);
351}
352
353void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
354                                          raw_ostream &OS) {
355  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
356  printBefore(T->getPointeeType(), OS);
357  OS << '^';
358}
359void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
360                                          raw_ostream &OS) {
361  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
362  printAfter(T->getPointeeType(), OS);
363}
364
365void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
366                                             raw_ostream &OS) {
367  IncludeStrongLifetimeRAII Strong(Policy);
368  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
369  printBefore(T->getPointeeTypeAsWritten(), OS);
370  // Handle things like 'int (&A)[4];' correctly.
371  // FIXME: this should include vectors, but vectors use attributes I guess.
372  if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
373    OS << '(';
374  OS << '&';
375}
376void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
377                                            raw_ostream &OS) {
378  IncludeStrongLifetimeRAII Strong(Policy);
379  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
380  // Handle things like 'int (&A)[4];' correctly.
381  // FIXME: this should include vectors, but vectors use attributes I guess.
382  if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
383    OS << ')';
384  printAfter(T->getPointeeTypeAsWritten(), OS);
385}
386
387void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
388                                             raw_ostream &OS) {
389  IncludeStrongLifetimeRAII Strong(Policy);
390  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
391  printBefore(T->getPointeeTypeAsWritten(), OS);
392  // Handle things like 'int (&&A)[4];' correctly.
393  // FIXME: this should include vectors, but vectors use attributes I guess.
394  if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
395    OS << '(';
396  OS << "&&";
397}
398void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
399                                            raw_ostream &OS) {
400  IncludeStrongLifetimeRAII Strong(Policy);
401  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
402  // Handle things like 'int (&&A)[4];' correctly.
403  // FIXME: this should include vectors, but vectors use attributes I guess.
404  if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
405    OS << ')';
406  printAfter(T->getPointeeTypeAsWritten(), OS);
407}
408
409void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
410                                           raw_ostream &OS) {
411  IncludeStrongLifetimeRAII Strong(Policy);
412  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
413  printBefore(T->getPointeeType(), OS);
414  // Handle things like 'int (Cls::*A)[4];' correctly.
415  // FIXME: this should include vectors, but vectors use attributes I guess.
416  if (isa<ArrayType>(T->getPointeeType()))
417    OS << '(';
418
419  PrintingPolicy InnerPolicy(Policy);
420  InnerPolicy.IncludeTagDefinition = false;
421  TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
422
423  OS << "::*";
424}
425void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
426                                          raw_ostream &OS) {
427  IncludeStrongLifetimeRAII Strong(Policy);
428  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
429  // Handle things like 'int (Cls::*A)[4];' correctly.
430  // FIXME: this should include vectors, but vectors use attributes I guess.
431  if (isa<ArrayType>(T->getPointeeType()))
432    OS << ')';
433  printAfter(T->getPointeeType(), OS);
434}
435
436void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
437                                           raw_ostream &OS) {
438  IncludeStrongLifetimeRAII Strong(Policy);
439  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
440  printBefore(T->getElementType(), OS);
441}
442void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
443                                          raw_ostream &OS) {
444  OS << '[';
445  if (T->getIndexTypeQualifiers().hasQualifiers()) {
446    AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
447                       Policy.Restrict);
448    OS << ' ';
449  }
450
451  if (T->getSizeModifier() == ArrayType::Static)
452    OS << "static ";
453
454  OS << T->getSize().getZExtValue() << ']';
455  printAfter(T->getElementType(), OS);
456}
457
458void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
459                                             raw_ostream &OS) {
460  IncludeStrongLifetimeRAII Strong(Policy);
461  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
462  printBefore(T->getElementType(), OS);
463}
464void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
465                                            raw_ostream &OS) {
466  OS << "[]";
467  printAfter(T->getElementType(), OS);
468}
469
470void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
471                                           raw_ostream &OS) {
472  IncludeStrongLifetimeRAII Strong(Policy);
473  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
474  printBefore(T->getElementType(), OS);
475}
476void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
477                                          raw_ostream &OS) {
478  OS << '[';
479  if (T->getIndexTypeQualifiers().hasQualifiers()) {
480    AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
481    OS << ' ';
482  }
483
484  if (T->getSizeModifier() == VariableArrayType::Static)
485    OS << "static ";
486  else if (T->getSizeModifier() == VariableArrayType::Star)
487    OS << '*';
488
489  if (T->getSizeExpr())
490    T->getSizeExpr()->printPretty(OS, nullptr, Policy);
491  OS << ']';
492
493  printAfter(T->getElementType(), OS);
494}
495
496void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
497  // Print the adjusted representation, otherwise the adjustment will be
498  // invisible.
499  printBefore(T->getAdjustedType(), OS);
500}
501void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
502  printAfter(T->getAdjustedType(), OS);
503}
504
505void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
506  // Print as though it's a pointer.
507  printAdjustedBefore(T, OS);
508}
509void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
510  printAdjustedAfter(T, OS);
511}
512
513void TypePrinter::printDependentSizedArrayBefore(
514                                               const DependentSizedArrayType *T,
515                                               raw_ostream &OS) {
516  IncludeStrongLifetimeRAII Strong(Policy);
517  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
518  printBefore(T->getElementType(), OS);
519}
520void TypePrinter::printDependentSizedArrayAfter(
521                                               const DependentSizedArrayType *T,
522                                               raw_ostream &OS) {
523  OS << '[';
524  if (T->getSizeExpr())
525    T->getSizeExpr()->printPretty(OS, nullptr, Policy);
526  OS << ']';
527  printAfter(T->getElementType(), OS);
528}
529
530void TypePrinter::printDependentSizedExtVectorBefore(
531                                          const DependentSizedExtVectorType *T,
532                                          raw_ostream &OS) {
533  printBefore(T->getElementType(), OS);
534}
535void TypePrinter::printDependentSizedExtVectorAfter(
536                                          const DependentSizedExtVectorType *T,
537                                          raw_ostream &OS) {
538  OS << " __attribute__((ext_vector_type(";
539  if (T->getSizeExpr())
540    T->getSizeExpr()->printPretty(OS, nullptr, Policy);
541  OS << ")))";
542  printAfter(T->getElementType(), OS);
543}
544
545void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
546  switch (T->getVectorKind()) {
547  case VectorType::AltiVecPixel:
548    OS << "__vector __pixel ";
549    break;
550  case VectorType::AltiVecBool:
551    OS << "__vector __bool ";
552    printBefore(T->getElementType(), OS);
553    break;
554  case VectorType::AltiVecVector:
555    OS << "__vector ";
556    printBefore(T->getElementType(), OS);
557    break;
558  case VectorType::NeonVector:
559    OS << "__attribute__((neon_vector_type("
560       << T->getNumElements() << "))) ";
561    printBefore(T->getElementType(), OS);
562    break;
563  case VectorType::NeonPolyVector:
564    OS << "__attribute__((neon_polyvector_type(" <<
565          T->getNumElements() << "))) ";
566    printBefore(T->getElementType(), OS);
567    break;
568  case VectorType::GenericVector: {
569    // FIXME: We prefer to print the size directly here, but have no way
570    // to get the size of the type.
571    OS << "__attribute__((__vector_size__("
572       << T->getNumElements()
573       << " * sizeof(";
574    print(T->getElementType(), OS, StringRef());
575    OS << ")))) ";
576    printBefore(T->getElementType(), OS);
577    break;
578  }
579  }
580}
581void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
582  printAfter(T->getElementType(), OS);
583}
584
585void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
586                                       raw_ostream &OS) {
587  printBefore(T->getElementType(), OS);
588}
589void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
590  printAfter(T->getElementType(), OS);
591  OS << " __attribute__((ext_vector_type(";
592  OS << T->getNumElements();
593  OS << ")))";
594}
595
596void
597FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
598                                               const PrintingPolicy &Policy)
599                                                                         const {
600
601  if (hasDynamicExceptionSpec()) {
602    OS << " throw(";
603    if (getExceptionSpecType() == EST_MSAny)
604      OS << "...";
605    else
606      for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
607        if (I)
608          OS << ", ";
609
610        OS << getExceptionType(I).stream(Policy);
611      }
612    OS << ')';
613  } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
614    OS << " noexcept";
615    if (getExceptionSpecType() == EST_ComputedNoexcept) {
616      OS << '(';
617      if (getNoexceptExpr())
618        getNoexceptExpr()->printPretty(OS, nullptr, Policy);
619      OS << ')';
620    }
621  }
622}
623
624void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
625                                           raw_ostream &OS) {
626  if (T->hasTrailingReturn()) {
627    OS << "auto ";
628    if (!HasEmptyPlaceHolder)
629      OS << '(';
630  } else {
631    // If needed for precedence reasons, wrap the inner part in grouping parens.
632    SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
633    printBefore(T->getReturnType(), OS);
634    if (!PrevPHIsEmpty.get())
635      OS << '(';
636  }
637}
638
639llvm::StringRef clang::getParameterABISpelling(ParameterABI ABI) {
640  switch (ABI) {
641  case ParameterABI::Ordinary:
642    llvm_unreachable("asking for spelling of ordinary parameter ABI");
643  case ParameterABI::SwiftContext:
644    return "swift_context";
645  case ParameterABI::SwiftErrorResult:
646    return "swift_error_result";
647  case ParameterABI::SwiftIndirectResult:
648    return "swift_indirect_result";
649  }
650  llvm_unreachable("bad parameter ABI kind");
651}
652
653void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
654                                          raw_ostream &OS) {
655  // If needed for precedence reasons, wrap the inner part in grouping parens.
656  if (!HasEmptyPlaceHolder)
657    OS << ')';
658  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
659
660  OS << '(';
661  {
662    ParamPolicyRAII ParamPolicy(Policy);
663    for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
664      if (i) OS << ", ";
665
666      auto EPI = T->getExtParameterInfo(i);
667      if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
668      auto ABI = EPI.getABI();
669      if (ABI != ParameterABI::Ordinary)
670        OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
671
672      print(T->getParamType(i), OS, StringRef());
673    }
674  }
675
676  if (T->isVariadic()) {
677    if (T->getNumParams())
678      OS << ", ";
679    OS << "...";
680  } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
681    // Do not emit int() if we have a proto, emit 'int(void)'.
682    OS << "void";
683  }
684
685  OS << ')';
686
687  FunctionType::ExtInfo Info = T->getExtInfo();
688
689  printFunctionAfter(Info, OS);
690
691  if (unsigned quals = T->getTypeQuals()) {
692    OS << ' ';
693    AppendTypeQualList(OS, quals, Policy.Restrict);
694  }
695
696  switch (T->getRefQualifier()) {
697  case RQ_None:
698    break;
699
700  case RQ_LValue:
701    OS << " &";
702    break;
703
704  case RQ_RValue:
705    OS << " &&";
706    break;
707  }
708  T->printExceptionSpecification(OS, Policy);
709
710  if (T->hasTrailingReturn()) {
711    OS << " -> ";
712    print(T->getReturnType(), OS, StringRef());
713  } else
714    printAfter(T->getReturnType(), OS);
715}
716
717void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
718                                     raw_ostream &OS) {
719  if (!InsideCCAttribute) {
720    switch (Info.getCC()) {
721    case CC_C:
722      // The C calling convention is the default on the vast majority of platforms
723      // we support.  If the user wrote it explicitly, it will usually be printed
724      // while traversing the AttributedType.  If the type has been desugared, let
725      // the canonical spelling be the implicit calling convention.
726      // FIXME: It would be better to be explicit in certain contexts, such as a
727      // cdecl function typedef used to declare a member function with the
728      // Microsoft C++ ABI.
729      break;
730    case CC_X86StdCall:
731      OS << " __attribute__((stdcall))";
732      break;
733    case CC_X86FastCall:
734      OS << " __attribute__((fastcall))";
735      break;
736    case CC_X86ThisCall:
737      OS << " __attribute__((thiscall))";
738      break;
739    case CC_X86VectorCall:
740      OS << " __attribute__((vectorcall))";
741      break;
742    case CC_X86Pascal:
743      OS << " __attribute__((pascal))";
744      break;
745    case CC_AAPCS:
746      OS << " __attribute__((pcs(\"aapcs\")))";
747      break;
748    case CC_AAPCS_VFP:
749      OS << " __attribute__((pcs(\"aapcs-vfp\")))";
750      break;
751    case CC_IntelOclBicc:
752      OS << " __attribute__((intel_ocl_bicc))";
753      break;
754    case CC_Win64:
755      OS << " __attribute__((ms_abi))";
756      break;
757    case CC_X86_64SysV:
758      OS << " __attribute__((sysv_abi))";
759      break;
760    case CC_X86RegCall:
761      OS << " __attribute__((regcall))";
762      break;
763    case CC_SpirFunction:
764    case CC_OpenCLKernel:
765      // Do nothing. These CCs are not available as attributes.
766      break;
767    case CC_Swift:
768      OS << " __attribute__((swiftcall))";
769      break;
770    case CC_PreserveMost:
771      OS << " __attribute__((preserve_most))";
772      break;
773    case CC_PreserveAll:
774      OS << " __attribute__((preserve_all))";
775      break;
776    }
777  }
778
779  if (Info.getNoReturn())
780    OS << " __attribute__((noreturn))";
781  if (Info.getProducesResult())
782    OS << " __attribute__((ns_returns_retained))";
783  if (Info.getRegParm())
784    OS << " __attribute__((regparm ("
785       << Info.getRegParm() << ")))";
786  if (Info.getNoCallerSavedRegs())
787    OS << " __attribute__((no_caller_saved_registers))";
788}
789
790void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
791                                             raw_ostream &OS) {
792  // If needed for precedence reasons, wrap the inner part in grouping parens.
793  SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
794  printBefore(T->getReturnType(), OS);
795  if (!PrevPHIsEmpty.get())
796    OS << '(';
797}
798void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
799                                            raw_ostream &OS) {
800  // If needed for precedence reasons, wrap the inner part in grouping parens.
801  if (!HasEmptyPlaceHolder)
802    OS << ')';
803  SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
804
805  OS << "()";
806  printFunctionAfter(T->getExtInfo(), OS);
807  printAfter(T->getReturnType(), OS);
808}
809
810void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
811
812  // Compute the full nested-name-specifier for this type.
813  // In C, this will always be empty except when the type
814  // being printed is anonymous within other Record.
815  if (!Policy.SuppressScope)
816    AppendScope(D->getDeclContext(), OS);
817
818  IdentifierInfo *II = D->getIdentifier();
819  OS << II->getName();
820  spaceBeforePlaceHolder(OS);
821}
822
823void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
824                                             raw_ostream &OS) {
825  printTypeSpec(T->getDecl(), OS);
826}
827void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
828                                             raw_ostream &OS) { }
829
830void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
831  printTypeSpec(T->getDecl(), OS);
832}
833void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) { }
834
835void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
836                                        raw_ostream &OS) {
837  OS << "typeof ";
838  if (T->getUnderlyingExpr())
839    T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
840  spaceBeforePlaceHolder(OS);
841}
842void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
843                                       raw_ostream &OS) { }
844
845void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
846  OS << "typeof(";
847  print(T->getUnderlyingType(), OS, StringRef());
848  OS << ')';
849  spaceBeforePlaceHolder(OS);
850}
851void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) { }
852
853void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
854  OS << "decltype(";
855  if (T->getUnderlyingExpr())
856    T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
857  OS << ')';
858  spaceBeforePlaceHolder(OS);
859}
860void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) { }
861
862void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
863                                            raw_ostream &OS) {
864  IncludeStrongLifetimeRAII Strong(Policy);
865
866  switch (T->getUTTKind()) {
867    case UnaryTransformType::EnumUnderlyingType:
868      OS << "__underlying_type(";
869      print(T->getBaseType(), OS, StringRef());
870      OS << ')';
871      spaceBeforePlaceHolder(OS);
872      return;
873  }
874
875  printBefore(T->getBaseType(), OS);
876}
877void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
878                                           raw_ostream &OS) {
879  IncludeStrongLifetimeRAII Strong(Policy);
880
881  switch (T->getUTTKind()) {
882    case UnaryTransformType::EnumUnderlyingType:
883      return;
884  }
885
886  printAfter(T->getBaseType(), OS);
887}
888
889void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
890  // If the type has been deduced, do not print 'auto'.
891  if (!T->getDeducedType().isNull()) {
892    printBefore(T->getDeducedType(), OS);
893  } else {
894    switch (T->getKeyword()) {
895    case AutoTypeKeyword::Auto: OS << "auto"; break;
896    case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
897    case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
898    }
899    spaceBeforePlaceHolder(OS);
900  }
901}
902void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
903  // If the type has been deduced, do not print 'auto'.
904  if (!T->getDeducedType().isNull())
905    printAfter(T->getDeducedType(), OS);
906}
907
908void TypePrinter::printDeducedTemplateSpecializationBefore(
909    const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
910  // If the type has been deduced, print the deduced type.
911  if (!T->getDeducedType().isNull()) {
912    printBefore(T->getDeducedType(), OS);
913  } else {
914    IncludeStrongLifetimeRAII Strong(Policy);
915    T->getTemplateName().print(OS, Policy);
916    spaceBeforePlaceHolder(OS);
917  }
918}
919void TypePrinter::printDeducedTemplateSpecializationAfter(
920    const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
921  // If the type has been deduced, print the deduced type.
922  if (!T->getDeducedType().isNull())
923    printAfter(T->getDeducedType(), OS);
924}
925
926void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
927  IncludeStrongLifetimeRAII Strong(Policy);
928
929  OS << "_Atomic(";
930  print(T->getValueType(), OS, StringRef());
931  OS << ')';
932  spaceBeforePlaceHolder(OS);
933}
934void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) { }
935
936void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
937  IncludeStrongLifetimeRAII Strong(Policy);
938
939  if (T->isReadOnly())
940    OS << "read_only ";
941  else
942    OS << "write_only ";
943  OS << "pipe ";
944  print(T->getElementType(), OS, StringRef());
945  spaceBeforePlaceHolder(OS);
946}
947
948void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {
949}
950/// Appends the given scope to the end of a string.
951void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
952  if (DC->isTranslationUnit()) return;
953  if (DC->isFunctionOrMethod()) return;
954  AppendScope(DC->getParent(), OS);
955
956  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
957    if (Policy.SuppressUnwrittenScope &&
958        (NS->isAnonymousNamespace() || NS->isInline()))
959      return;
960    if (NS->getIdentifier())
961      OS << NS->getName() << "::";
962    else
963      OS << "(anonymous namespace)::";
964  } else if (ClassTemplateSpecializationDecl *Spec
965               = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
966    IncludeStrongLifetimeRAII Strong(Policy);
967    OS << Spec->getIdentifier()->getName();
968    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
969    TemplateSpecializationType::PrintTemplateArgumentList(
970        OS, TemplateArgs.asArray(), Policy);
971    OS << "::";
972  } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
973    if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
974      OS << Typedef->getIdentifier()->getName() << "::";
975    else if (Tag->getIdentifier())
976      OS << Tag->getIdentifier()->getName() << "::";
977    else
978      return;
979  }
980}
981
982void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
983  if (Policy.IncludeTagDefinition) {
984    PrintingPolicy SubPolicy = Policy;
985    SubPolicy.IncludeTagDefinition = false;
986    D->print(OS, SubPolicy, Indentation);
987    spaceBeforePlaceHolder(OS);
988    return;
989  }
990
991  bool HasKindDecoration = false;
992
993  // We don't print tags unless this is an elaborated type.
994  // In C, we just assume every RecordType is an elaborated type.
995  if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
996    HasKindDecoration = true;
997    OS << D->getKindName();
998    OS << ' ';
999  }
1000
1001  // Compute the full nested-name-specifier for this type.
1002  // In C, this will always be empty except when the type
1003  // being printed is anonymous within other Record.
1004  if (!Policy.SuppressScope)
1005    AppendScope(D->getDeclContext(), OS);
1006
1007  if (const IdentifierInfo *II = D->getIdentifier())
1008    OS << II->getName();
1009  else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1010    assert(Typedef->getIdentifier() && "Typedef without identifier?");
1011    OS << Typedef->getIdentifier()->getName();
1012  } else {
1013    // Make an unambiguous representation for anonymous types, e.g.
1014    //   (anonymous enum at /usr/include/string.h:120:9)
1015    OS << (Policy.MSVCFormatting ? '`' : '(');
1016
1017    if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1018      OS << "lambda";
1019      HasKindDecoration = true;
1020    } else {
1021      OS << "anonymous";
1022    }
1023
1024    if (Policy.AnonymousTagLocations) {
1025      // Suppress the redundant tag keyword if we just printed one.
1026      // We don't have to worry about ElaboratedTypes here because you can't
1027      // refer to an anonymous type with one.
1028      if (!HasKindDecoration)
1029        OS << " " << D->getKindName();
1030
1031      PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1032          D->getLocation());
1033      if (PLoc.isValid()) {
1034        OS << " at " << PLoc.getFilename()
1035           << ':' << PLoc.getLine()
1036           << ':' << PLoc.getColumn();
1037      }
1038    }
1039
1040    OS << (Policy.MSVCFormatting ? '\'' : ')');
1041  }
1042
1043  // If this is a class template specialization, print the template
1044  // arguments.
1045  if (ClassTemplateSpecializationDecl *Spec
1046        = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1047    ArrayRef<TemplateArgument> Args;
1048    if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
1049      const TemplateSpecializationType *TST =
1050        cast<TemplateSpecializationType>(TAW->getType());
1051      Args = TST->template_arguments();
1052    } else {
1053      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1054      Args = TemplateArgs.asArray();
1055    }
1056    IncludeStrongLifetimeRAII Strong(Policy);
1057    TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, Policy);
1058  }
1059
1060  spaceBeforePlaceHolder(OS);
1061}
1062
1063void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1064  printTag(T->getDecl(), OS);
1065}
1066void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) { }
1067
1068void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1069  printTag(T->getDecl(), OS);
1070}
1071void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) { }
1072
1073void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1074                                              raw_ostream &OS) {
1075  if (IdentifierInfo *Id = T->getIdentifier())
1076    OS << Id->getName();
1077  else
1078    OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1079  spaceBeforePlaceHolder(OS);
1080}
1081void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1082                                             raw_ostream &OS) { }
1083
1084void TypePrinter::printSubstTemplateTypeParmBefore(
1085                                             const SubstTemplateTypeParmType *T,
1086                                             raw_ostream &OS) {
1087  IncludeStrongLifetimeRAII Strong(Policy);
1088  printBefore(T->getReplacementType(), OS);
1089}
1090void TypePrinter::printSubstTemplateTypeParmAfter(
1091                                             const SubstTemplateTypeParmType *T,
1092                                             raw_ostream &OS) {
1093  IncludeStrongLifetimeRAII Strong(Policy);
1094  printAfter(T->getReplacementType(), OS);
1095}
1096
1097void TypePrinter::printSubstTemplateTypeParmPackBefore(
1098                                        const SubstTemplateTypeParmPackType *T,
1099                                        raw_ostream &OS) {
1100  IncludeStrongLifetimeRAII Strong(Policy);
1101  printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1102}
1103void TypePrinter::printSubstTemplateTypeParmPackAfter(
1104                                        const SubstTemplateTypeParmPackType *T,
1105                                        raw_ostream &OS) {
1106  IncludeStrongLifetimeRAII Strong(Policy);
1107  printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1108}
1109
1110void TypePrinter::printTemplateSpecializationBefore(
1111                                            const TemplateSpecializationType *T,
1112                                            raw_ostream &OS) {
1113  IncludeStrongLifetimeRAII Strong(Policy);
1114  T->getTemplateName().print(OS, Policy);
1115
1116  TemplateSpecializationType::PrintTemplateArgumentList(
1117      OS, T->template_arguments(), Policy);
1118  spaceBeforePlaceHolder(OS);
1119}
1120void TypePrinter::printTemplateSpecializationAfter(
1121                                            const TemplateSpecializationType *T,
1122                                            raw_ostream &OS) { }
1123
1124void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1125                                               raw_ostream &OS) {
1126  printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1127}
1128void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1129                                               raw_ostream &OS) { }
1130
1131void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1132                                        raw_ostream &OS) {
1133  // The tag definition will take care of these.
1134  if (!Policy.IncludeTagDefinition)
1135  {
1136    OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1137    if (T->getKeyword() != ETK_None)
1138      OS << " ";
1139    NestedNameSpecifier* Qualifier = T->getQualifier();
1140    if (Qualifier)
1141      Qualifier->print(OS, Policy);
1142  }
1143
1144  ElaboratedTypePolicyRAII PolicyRAII(Policy);
1145  printBefore(T->getNamedType(), OS);
1146}
1147void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1148                                        raw_ostream &OS) {
1149  ElaboratedTypePolicyRAII PolicyRAII(Policy);
1150  printAfter(T->getNamedType(), OS);
1151}
1152
1153void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1154  if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1155    printBefore(T->getInnerType(), OS);
1156    OS << '(';
1157  } else
1158    printBefore(T->getInnerType(), OS);
1159}
1160void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1161  if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1162    OS << ')';
1163    printAfter(T->getInnerType(), OS);
1164  } else
1165    printAfter(T->getInnerType(), OS);
1166}
1167
1168void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1169                                           raw_ostream &OS) {
1170  OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1171  if (T->getKeyword() != ETK_None)
1172    OS << " ";
1173
1174  T->getQualifier()->print(OS, Policy);
1175
1176  OS << T->getIdentifier()->getName();
1177  spaceBeforePlaceHolder(OS);
1178}
1179void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1180                                          raw_ostream &OS) { }
1181
1182void TypePrinter::printDependentTemplateSpecializationBefore(
1183        const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1184  IncludeStrongLifetimeRAII Strong(Policy);
1185
1186  OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1187  if (T->getKeyword() != ETK_None)
1188    OS << " ";
1189
1190  if (T->getQualifier())
1191    T->getQualifier()->print(OS, Policy);
1192  OS << T->getIdentifier()->getName();
1193  TemplateSpecializationType::PrintTemplateArgumentList(OS,
1194                                                        T->template_arguments(),
1195                                                        Policy);
1196  spaceBeforePlaceHolder(OS);
1197}
1198void TypePrinter::printDependentTemplateSpecializationAfter(
1199        const DependentTemplateSpecializationType *T, raw_ostream &OS) { }
1200
1201void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1202                                           raw_ostream &OS) {
1203  printBefore(T->getPattern(), OS);
1204}
1205void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1206                                          raw_ostream &OS) {
1207  printAfter(T->getPattern(), OS);
1208  OS << "...";
1209}
1210
1211void TypePrinter::printAttributedBefore(const AttributedType *T,
1212                                        raw_ostream &OS) {
1213  // Prefer the macro forms of the GC and ownership qualifiers.
1214  if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1215      T->getAttrKind() == AttributedType::attr_objc_ownership)
1216    return printBefore(T->getEquivalentType(), OS);
1217
1218  if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1219    OS << "__kindof ";
1220
1221  printBefore(T->getModifiedType(), OS);
1222
1223  if (T->isMSTypeSpec()) {
1224    switch (T->getAttrKind()) {
1225    default: return;
1226    case AttributedType::attr_ptr32: OS << " __ptr32"; break;
1227    case AttributedType::attr_ptr64: OS << " __ptr64"; break;
1228    case AttributedType::attr_sptr: OS << " __sptr"; break;
1229    case AttributedType::attr_uptr: OS << " __uptr"; break;
1230    }
1231    spaceBeforePlaceHolder(OS);
1232  }
1233
1234  // Print nullability type specifiers.
1235  if (T->getAttrKind() == AttributedType::attr_nonnull ||
1236      T->getAttrKind() == AttributedType::attr_nullable ||
1237      T->getAttrKind() == AttributedType::attr_null_unspecified) {
1238    if (T->getAttrKind() == AttributedType::attr_nonnull)
1239      OS << " _Nonnull";
1240    else if (T->getAttrKind() == AttributedType::attr_nullable)
1241      OS << " _Nullable";
1242    else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1243      OS << " _Null_unspecified";
1244    else
1245      llvm_unreachable("unhandled nullability");
1246    spaceBeforePlaceHolder(OS);
1247  }
1248}
1249
1250void TypePrinter::printAttributedAfter(const AttributedType *T,
1251                                       raw_ostream &OS) {
1252  // Prefer the macro forms of the GC and ownership qualifiers.
1253  if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1254      T->getAttrKind() == AttributedType::attr_objc_ownership)
1255    return printAfter(T->getEquivalentType(), OS);
1256
1257  if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1258    return;
1259
1260  // TODO: not all attributes are GCC-style attributes.
1261  if (T->isMSTypeSpec())
1262    return;
1263
1264  // Nothing to print after.
1265  if (T->getAttrKind() == AttributedType::attr_nonnull ||
1266      T->getAttrKind() == AttributedType::attr_nullable ||
1267      T->getAttrKind() == AttributedType::attr_null_unspecified)
1268    return printAfter(T->getModifiedType(), OS);
1269
1270  // If this is a calling convention attribute, don't print the implicit CC from
1271  // the modified type.
1272  SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1273
1274  printAfter(T->getModifiedType(), OS);
1275
1276  // Don't print the inert __unsafe_unretained attribute at all.
1277  if (T->getAttrKind() == AttributedType::attr_objc_inert_unsafe_unretained)
1278    return;
1279
1280  // Don't print ns_returns_retained unless it had an effect.
1281  if (T->getAttrKind() == AttributedType::attr_ns_returns_retained &&
1282      !T->getEquivalentType()->castAs<FunctionType>()
1283                             ->getExtInfo().getProducesResult())
1284    return;
1285
1286  // Print nullability type specifiers that occur after
1287  if (T->getAttrKind() == AttributedType::attr_nonnull ||
1288      T->getAttrKind() == AttributedType::attr_nullable ||
1289      T->getAttrKind() == AttributedType::attr_null_unspecified) {
1290    if (T->getAttrKind() == AttributedType::attr_nonnull)
1291      OS << " _Nonnull";
1292    else if (T->getAttrKind() == AttributedType::attr_nullable)
1293      OS << " _Nullable";
1294    else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1295      OS << " _Null_unspecified";
1296    else
1297      llvm_unreachable("unhandled nullability");
1298
1299    return;
1300  }
1301
1302  OS << " __attribute__((";
1303  switch (T->getAttrKind()) {
1304  default: llvm_unreachable("This attribute should have been handled already");
1305  case AttributedType::attr_address_space:
1306    OS << "address_space(";
1307    OS << T->getEquivalentType().getAddressSpace();
1308    OS << ')';
1309    break;
1310
1311  case AttributedType::attr_vector_size: {
1312    OS << "__vector_size__(";
1313    if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
1314      OS << vector->getNumElements();
1315      OS << " * sizeof(";
1316      print(vector->getElementType(), OS, StringRef());
1317      OS << ')';
1318    }
1319    OS << ')';
1320    break;
1321  }
1322
1323  case AttributedType::attr_neon_vector_type:
1324  case AttributedType::attr_neon_polyvector_type: {
1325    if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1326      OS << "neon_vector_type(";
1327    else
1328      OS << "neon_polyvector_type(";
1329    const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
1330    OS << vector->getNumElements();
1331    OS << ')';
1332    break;
1333  }
1334
1335  case AttributedType::attr_regparm: {
1336    // FIXME: When Sema learns to form this AttributedType, avoid printing the
1337    // attribute again in printFunctionProtoAfter.
1338    OS << "regparm(";
1339    QualType t = T->getEquivalentType();
1340    while (!t->isFunctionType())
1341      t = t->getPointeeType();
1342    OS << t->getAs<FunctionType>()->getRegParmType();
1343    OS << ')';
1344    break;
1345  }
1346
1347  case AttributedType::attr_objc_gc: {
1348    OS << "objc_gc(";
1349
1350    QualType tmp = T->getEquivalentType();
1351    while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
1352      QualType next = tmp->getPointeeType();
1353      if (next == tmp) break;
1354      tmp = next;
1355    }
1356
1357    if (tmp.isObjCGCWeak())
1358      OS << "weak";
1359    else
1360      OS << "strong";
1361    OS << ')';
1362    break;
1363  }
1364
1365  case AttributedType::attr_objc_ownership:
1366    OS << "objc_ownership(";
1367    switch (T->getEquivalentType().getObjCLifetime()) {
1368    case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
1369    case Qualifiers::OCL_ExplicitNone: OS << "none"; break;
1370    case Qualifiers::OCL_Strong: OS << "strong"; break;
1371    case Qualifiers::OCL_Weak: OS << "weak"; break;
1372    case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break;
1373    }
1374    OS << ')';
1375    break;
1376
1377  case AttributedType::attr_ns_returns_retained:
1378    OS << "ns_returns_retained";
1379    break;
1380
1381  // FIXME: When Sema learns to form this AttributedType, avoid printing the
1382  // attribute again in printFunctionProtoAfter.
1383  case AttributedType::attr_noreturn: OS << "noreturn"; break;
1384
1385  case AttributedType::attr_cdecl: OS << "cdecl"; break;
1386  case AttributedType::attr_fastcall: OS << "fastcall"; break;
1387  case AttributedType::attr_stdcall: OS << "stdcall"; break;
1388  case AttributedType::attr_thiscall: OS << "thiscall"; break;
1389  case AttributedType::attr_swiftcall: OS << "swiftcall"; break;
1390  case AttributedType::attr_vectorcall: OS << "vectorcall"; break;
1391  case AttributedType::attr_pascal: OS << "pascal"; break;
1392  case AttributedType::attr_ms_abi: OS << "ms_abi"; break;
1393  case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break;
1394  case AttributedType::attr_regcall: OS << "regcall"; break;
1395  case AttributedType::attr_pcs:
1396  case AttributedType::attr_pcs_vfp: {
1397    OS << "pcs(";
1398   QualType t = T->getEquivalentType();
1399   while (!t->isFunctionType())
1400     t = t->getPointeeType();
1401   OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1402         "\"aapcs\"" : "\"aapcs-vfp\"");
1403   OS << ')';
1404   break;
1405  }
1406  case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1407  case AttributedType::attr_preserve_most:
1408    OS << "preserve_most";
1409    break;
1410  case AttributedType::attr_preserve_all:
1411    OS << "preserve_all";
1412    break;
1413  }
1414  OS << "))";
1415}
1416
1417void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1418                                           raw_ostream &OS) {
1419  OS << T->getDecl()->getName();
1420  spaceBeforePlaceHolder(OS);
1421}
1422void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1423                                          raw_ostream &OS) { }
1424
1425void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1426                                          raw_ostream &OS) {
1427  OS << T->getDecl()->getName();
1428  if (!T->qual_empty()) {
1429    bool isFirst = true;
1430    OS << '<';
1431    for (const auto *I : T->quals()) {
1432      if (isFirst)
1433        isFirst = false;
1434      else
1435        OS << ',';
1436      OS << I->getName();
1437    }
1438    OS << '>';
1439  }
1440
1441  spaceBeforePlaceHolder(OS);
1442}
1443
1444void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1445                                          raw_ostream &OS) { }
1446
1447void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1448                                        raw_ostream &OS) {
1449  if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1450      !T->isKindOfTypeAsWritten())
1451    return printBefore(T->getBaseType(), OS);
1452
1453  if (T->isKindOfTypeAsWritten())
1454    OS << "__kindof ";
1455
1456  print(T->getBaseType(), OS, StringRef());
1457
1458  if (T->isSpecializedAsWritten()) {
1459    bool isFirst = true;
1460    OS << '<';
1461    for (auto typeArg : T->getTypeArgsAsWritten()) {
1462      if (isFirst)
1463        isFirst = false;
1464      else
1465        OS << ",";
1466
1467      print(typeArg, OS, StringRef());
1468    }
1469    OS << '>';
1470  }
1471
1472  if (!T->qual_empty()) {
1473    bool isFirst = true;
1474    OS << '<';
1475    for (const auto *I : T->quals()) {
1476      if (isFirst)
1477        isFirst = false;
1478      else
1479        OS << ',';
1480      OS << I->getName();
1481    }
1482    OS << '>';
1483  }
1484
1485  spaceBeforePlaceHolder(OS);
1486}
1487void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1488                                        raw_ostream &OS) {
1489  if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1490      !T->isKindOfTypeAsWritten())
1491    return printAfter(T->getBaseType(), OS);
1492}
1493
1494void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1495                                               raw_ostream &OS) {
1496  printBefore(T->getPointeeType(), OS);
1497
1498  // If we need to print the pointer, print it now.
1499  if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1500      !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1501    if (HasEmptyPlaceHolder)
1502      OS << ' ';
1503    OS << '*';
1504  }
1505}
1506void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1507                                              raw_ostream &OS) { }
1508
1509void TemplateSpecializationType::
1510  PrintTemplateArgumentList(raw_ostream &OS,
1511                            const TemplateArgumentListInfo &Args,
1512                            const PrintingPolicy &Policy) {
1513  return PrintTemplateArgumentList(OS,
1514                                   Args.arguments(),
1515                                   Policy);
1516}
1517
1518void TemplateSpecializationType::PrintTemplateArgumentList(
1519    raw_ostream &OS, ArrayRef<TemplateArgument> Args,
1520    const PrintingPolicy &Policy, bool SkipBrackets) {
1521  const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1522  if (!SkipBrackets)
1523    OS << '<';
1524
1525  bool needSpace = false;
1526  bool FirstArg = true;
1527  for (const TemplateArgument &Arg : Args) {
1528    // Print the argument into a string.
1529    SmallString<128> Buf;
1530    llvm::raw_svector_ostream ArgOS(Buf);
1531    if (Arg.getKind() == TemplateArgument::Pack) {
1532      if (Arg.pack_size() && !FirstArg)
1533        OS << Comma;
1534      PrintTemplateArgumentList(ArgOS,
1535                                Arg.getPackAsArray(),
1536                                Policy, true);
1537    } else {
1538      if (!FirstArg)
1539        OS << Comma;
1540      Arg.print(Policy, ArgOS);
1541    }
1542    StringRef ArgString = ArgOS.str();
1543
1544    // If this is the first argument and its string representation
1545    // begins with the global scope specifier ('::foo'), add a space
1546    // to avoid printing the diagraph '<:'.
1547    if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
1548      OS << ' ';
1549
1550    OS << ArgString;
1551
1552    needSpace = (!ArgString.empty() && ArgString.back() == '>');
1553    FirstArg = false;
1554  }
1555
1556  // If the last character of our string is '>', add another space to
1557  // keep the two '>''s separate tokens. We don't *have* to do this in
1558  // C++0x, but it's still good hygiene.
1559  if (needSpace)
1560    OS << ' ';
1561
1562  if (!SkipBrackets)
1563    OS << '>';
1564}
1565
1566// Sadly, repeat all that with TemplateArgLoc.
1567void TemplateSpecializationType::
1568PrintTemplateArgumentList(raw_ostream &OS,
1569                          ArrayRef<TemplateArgumentLoc> Args,
1570                          const PrintingPolicy &Policy) {
1571  OS << '<';
1572  const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1573
1574  bool needSpace = false;
1575  bool FirstArg = true;
1576  for (const TemplateArgumentLoc &Arg : Args) {
1577    if (!FirstArg)
1578      OS << Comma;
1579
1580    // Print the argument into a string.
1581    SmallString<128> Buf;
1582    llvm::raw_svector_ostream ArgOS(Buf);
1583    if (Arg.getArgument().getKind() == TemplateArgument::Pack) {
1584      PrintTemplateArgumentList(ArgOS,
1585                                Arg.getArgument().getPackAsArray(),
1586                                Policy, true);
1587    } else {
1588      Arg.getArgument().print(Policy, ArgOS);
1589    }
1590    StringRef ArgString = ArgOS.str();
1591
1592    // If this is the first argument and its string representation
1593    // begins with the global scope specifier ('::foo'), add a space
1594    // to avoid printing the diagraph '<:'.
1595    if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
1596      OS << ' ';
1597
1598    OS << ArgString;
1599
1600    needSpace = (!ArgString.empty() && ArgString.back() == '>');
1601    FirstArg = false;
1602  }
1603
1604  // If the last character of our string is '>', add another space to
1605  // keep the two '>''s separate tokens. We don't *have* to do this in
1606  // C++0x, but it's still good hygiene.
1607  if (needSpace)
1608    OS << ' ';
1609
1610  OS << '>';
1611}
1612
1613std::string Qualifiers::getAsString() const {
1614  LangOptions LO;
1615  return getAsString(PrintingPolicy(LO));
1616}
1617
1618// Appends qualifiers to the given string, separated by spaces.  Will
1619// prefix a space if the string is non-empty.  Will not append a final
1620// space.
1621std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1622  SmallString<64> Buf;
1623  llvm::raw_svector_ostream StrOS(Buf);
1624  print(StrOS, Policy);
1625  return StrOS.str();
1626}
1627
1628bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1629  if (getCVRQualifiers())
1630    return false;
1631
1632  if (getAddressSpace())
1633    return false;
1634
1635  if (getObjCGCAttr())
1636    return false;
1637
1638  if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1639    if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1640      return false;
1641
1642  return true;
1643}
1644
1645// Appends qualifiers to the given string, separated by spaces.  Will
1646// prefix a space if the string is non-empty.  Will not append a final
1647// space.
1648void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1649                       bool appendSpaceIfNonEmpty) const {
1650  bool addSpace = false;
1651
1652  unsigned quals = getCVRQualifiers();
1653  if (quals) {
1654    AppendTypeQualList(OS, quals, Policy.Restrict);
1655    addSpace = true;
1656  }
1657  if (hasUnaligned()) {
1658    if (addSpace)
1659      OS << ' ';
1660    OS << "__unaligned";
1661    addSpace = true;
1662  }
1663  if (unsigned addrspace = getAddressSpace()) {
1664    if (addSpace)
1665      OS << ' ';
1666    addSpace = true;
1667    switch (addrspace) {
1668      case LangAS::opencl_global:
1669        OS << "__global";
1670        break;
1671      case LangAS::opencl_local:
1672        OS << "__local";
1673        break;
1674      case LangAS::opencl_constant:
1675      case LangAS::cuda_constant:
1676        OS << "__constant";
1677        break;
1678      case LangAS::opencl_generic:
1679        OS << "__generic";
1680        break;
1681      case LangAS::cuda_device:
1682        OS << "__device";
1683        break;
1684      case LangAS::cuda_shared:
1685        OS << "__shared";
1686        break;
1687      default:
1688        assert(addrspace >= LangAS::FirstTargetAddressSpace);
1689        OS << "__attribute__((address_space(";
1690        OS << addrspace - LangAS::FirstTargetAddressSpace;
1691        OS << ")))";
1692    }
1693  }
1694  if (Qualifiers::GC gc = getObjCGCAttr()) {
1695    if (addSpace)
1696      OS << ' ';
1697    addSpace = true;
1698    if (gc == Qualifiers::Weak)
1699      OS << "__weak";
1700    else
1701      OS << "__strong";
1702  }
1703  if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1704    if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1705      if (addSpace)
1706        OS << ' ';
1707      addSpace = true;
1708    }
1709
1710    switch (lifetime) {
1711    case Qualifiers::OCL_None: llvm_unreachable("none but true");
1712    case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1713    case Qualifiers::OCL_Strong:
1714      if (!Policy.SuppressStrongLifetime)
1715        OS << "__strong";
1716      break;
1717
1718    case Qualifiers::OCL_Weak: OS << "__weak"; break;
1719    case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1720    }
1721  }
1722
1723  if (appendSpaceIfNonEmpty && addSpace)
1724    OS << ' ';
1725}
1726
1727std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1728  std::string S;
1729  getAsStringInternal(S, Policy);
1730  return S;
1731}
1732
1733std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1734  std::string buffer;
1735  LangOptions options;
1736  getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1737  return buffer;
1738}
1739
1740void QualType::print(const Type *ty, Qualifiers qs,
1741                     raw_ostream &OS, const PrintingPolicy &policy,
1742                     const Twine &PlaceHolder, unsigned Indentation) {
1743  SmallString<128> PHBuf;
1744  StringRef PH = PlaceHolder.toStringRef(PHBuf);
1745
1746  TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
1747}
1748
1749void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1750                                   std::string &buffer,
1751                                   const PrintingPolicy &policy) {
1752  SmallString<256> Buf;
1753  llvm::raw_svector_ostream StrOS(Buf);
1754  TypePrinter(policy).print(ty, qs, StrOS, buffer);
1755  std::string str = StrOS.str();
1756  buffer.swap(str);
1757}
1758