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