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