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