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