1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to print types from Clang's type system.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TemplateName.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/AddressSpaces.h"
27 #include "clang/Basic/ExceptionSpecificationType.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/Specifiers.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/SaveAndRestore.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <string>
45 
46 using namespace clang;
47 
48 namespace {
49 
50   /// RAII object that enables printing of the ARC __strong lifetime
51   /// qualifier.
52   class IncludeStrongLifetimeRAII {
53     PrintingPolicy &Policy;
54     bool Old;
55 
56   public:
57     explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
58         : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
59         if (!Policy.SuppressLifetimeQualifiers)
60           Policy.SuppressStrongLifetime = false;
61     }
62 
63     ~IncludeStrongLifetimeRAII() {
64       Policy.SuppressStrongLifetime = Old;
65     }
66   };
67 
68   class ParamPolicyRAII {
69     PrintingPolicy &Policy;
70     bool Old;
71 
72   public:
73     explicit ParamPolicyRAII(PrintingPolicy &Policy)
74         : Policy(Policy), Old(Policy.SuppressSpecifiers) {
75       Policy.SuppressSpecifiers = false;
76     }
77 
78     ~ParamPolicyRAII() {
79       Policy.SuppressSpecifiers = Old;
80     }
81   };
82 
83   class ElaboratedTypePolicyRAII {
84     PrintingPolicy &Policy;
85     bool SuppressTagKeyword;
86     bool SuppressScope;
87 
88   public:
89     explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
90       SuppressTagKeyword = Policy.SuppressTagKeyword;
91       SuppressScope = Policy.SuppressScope;
92       Policy.SuppressTagKeyword = true;
93       Policy.SuppressScope = true;
94     }
95 
96     ~ElaboratedTypePolicyRAII() {
97       Policy.SuppressTagKeyword = SuppressTagKeyword;
98       Policy.SuppressScope = SuppressScope;
99     }
100   };
101 
102   class TypePrinter {
103     PrintingPolicy Policy;
104     unsigned Indentation;
105     bool HasEmptyPlaceHolder = false;
106     bool InsideCCAttribute = false;
107 
108   public:
109     explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
110         : Policy(Policy), Indentation(Indentation) {}
111 
112     void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
113                StringRef PlaceHolder);
114     void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
115 
116     static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
117     void spaceBeforePlaceHolder(raw_ostream &OS);
118     void printTypeSpec(NamedDecl *D, raw_ostream &OS);
119     void printTemplateId(const TemplateSpecializationType *T, raw_ostream &OS,
120                          bool FullyQualify);
121 
122     void printBefore(QualType T, raw_ostream &OS);
123     void printAfter(QualType T, raw_ostream &OS);
124     void AppendScope(DeclContext *DC, raw_ostream &OS,
125                      DeclarationName NameInScope);
126     void printTag(TagDecl *T, raw_ostream &OS);
127     void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
128 #define ABSTRACT_TYPE(CLASS, PARENT)
129 #define TYPE(CLASS, PARENT) \
130     void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
131     void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
132 #include "clang/AST/TypeNodes.inc"
133 
134   private:
135     void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
136     void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
137   };
138 
139 } // namespace
140 
141 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
142                                bool HasRestrictKeyword) {
143   bool appendSpace = false;
144   if (TypeQuals & Qualifiers::Const) {
145     OS << "const";
146     appendSpace = true;
147   }
148   if (TypeQuals & Qualifiers::Volatile) {
149     if (appendSpace) OS << ' ';
150     OS << "volatile";
151     appendSpace = true;
152   }
153   if (TypeQuals & Qualifiers::Restrict) {
154     if (appendSpace) OS << ' ';
155     if (HasRestrictKeyword) {
156       OS << "restrict";
157     } else {
158       OS << "__restrict";
159     }
160   }
161 }
162 
163 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
164   if (!HasEmptyPlaceHolder)
165     OS << ' ';
166 }
167 
168 static SplitQualType splitAccordingToPolicy(QualType QT,
169                                             const PrintingPolicy &Policy) {
170   if (Policy.PrintCanonicalTypes)
171     QT = QT.getCanonicalType();
172   return QT.split();
173 }
174 
175 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
176   SplitQualType split = splitAccordingToPolicy(t, Policy);
177   print(split.Ty, split.Quals, OS, PlaceHolder);
178 }
179 
180 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
181                         StringRef PlaceHolder) {
182   if (!T) {
183     OS << "NULL TYPE";
184     return;
185   }
186 
187   SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
188 
189   printBefore(T, Quals, OS);
190   OS << PlaceHolder;
191   printAfter(T, Quals, OS);
192 }
193 
194 bool TypePrinter::canPrefixQualifiers(const Type *T,
195                                       bool &NeedARCStrongQualifier) {
196   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
197   // so that we get "const int" instead of "int const", but we can't do this if
198   // the type is complex.  For example if the type is "int*", we *must* print
199   // "int * const", printing "const int *" is different.  Only do this when the
200   // type expands to a simple string.
201   bool CanPrefixQualifiers = false;
202   NeedARCStrongQualifier = false;
203   const Type *UnderlyingType = T;
204   if (const auto *AT = dyn_cast<AutoType>(T))
205     UnderlyingType = AT->desugar().getTypePtr();
206   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
207     UnderlyingType = Subst->getReplacementType().getTypePtr();
208   Type::TypeClass TC = UnderlyingType->getTypeClass();
209 
210   switch (TC) {
211     case Type::Auto:
212     case Type::Builtin:
213     case Type::Complex:
214     case Type::UnresolvedUsing:
215     case Type::Typedef:
216     case Type::TypeOfExpr:
217     case Type::TypeOf:
218     case Type::Decltype:
219     case Type::UnaryTransform:
220     case Type::Record:
221     case Type::Enum:
222     case Type::Elaborated:
223     case Type::TemplateTypeParm:
224     case Type::SubstTemplateTypeParmPack:
225     case Type::DeducedTemplateSpecialization:
226     case Type::TemplateSpecialization:
227     case Type::InjectedClassName:
228     case Type::DependentName:
229     case Type::DependentTemplateSpecialization:
230     case Type::ObjCObject:
231     case Type::ObjCTypeParam:
232     case Type::ObjCInterface:
233     case Type::Atomic:
234     case Type::Pipe:
235     case Type::ExtInt:
236     case Type::DependentExtInt:
237       CanPrefixQualifiers = true;
238       break;
239 
240     case Type::ObjCObjectPointer:
241       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
242         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
243       break;
244 
245     case Type::VariableArray:
246     case Type::DependentSizedArray:
247       NeedARCStrongQualifier = true;
248       LLVM_FALLTHROUGH;
249 
250     case Type::ConstantArray:
251     case Type::IncompleteArray:
252       return canPrefixQualifiers(
253           cast<ArrayType>(UnderlyingType)->getElementType().getTypePtr(),
254           NeedARCStrongQualifier);
255 
256     case Type::Adjusted:
257     case Type::Decayed:
258     case Type::Pointer:
259     case Type::BlockPointer:
260     case Type::LValueReference:
261     case Type::RValueReference:
262     case Type::MemberPointer:
263     case Type::DependentAddressSpace:
264     case Type::DependentVector:
265     case Type::DependentSizedExtVector:
266     case Type::Vector:
267     case Type::ExtVector:
268     case Type::ConstantMatrix:
269     case Type::DependentSizedMatrix:
270     case Type::FunctionProto:
271     case Type::FunctionNoProto:
272     case Type::Paren:
273     case Type::PackExpansion:
274     case Type::SubstTemplateTypeParm:
275     case Type::MacroQualified:
276       CanPrefixQualifiers = false;
277       break;
278 
279     case Type::Attributed: {
280       // We still want to print the address_space before the type if it is an
281       // address_space attribute.
282       const auto *AttrTy = cast<AttributedType>(T);
283       CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace;
284     }
285   }
286 
287   return CanPrefixQualifiers;
288 }
289 
290 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
291   SplitQualType Split = splitAccordingToPolicy(T, Policy);
292 
293   // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
294   // at this level.
295   Qualifiers Quals = Split.Quals;
296   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
297     Quals -= QualType(Subst, 0).getQualifiers();
298 
299   printBefore(Split.Ty, Quals, OS);
300 }
301 
302 /// Prints the part of the type string before an identifier, e.g. for
303 /// "int foo[10]" it prints "int ".
304 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
305   if (Policy.SuppressSpecifiers && T->isSpecifierType())
306     return;
307 
308   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
309 
310   // Print qualifiers as appropriate.
311 
312   bool CanPrefixQualifiers = false;
313   bool NeedARCStrongQualifier = false;
314   CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
315 
316   if (CanPrefixQualifiers && !Quals.empty()) {
317     if (NeedARCStrongQualifier) {
318       IncludeStrongLifetimeRAII Strong(Policy);
319       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
320     } else {
321       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
322     }
323   }
324 
325   bool hasAfterQuals = false;
326   if (!CanPrefixQualifiers && !Quals.empty()) {
327     hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
328     if (hasAfterQuals)
329       HasEmptyPlaceHolder = false;
330   }
331 
332   switch (T->getTypeClass()) {
333 #define ABSTRACT_TYPE(CLASS, PARENT)
334 #define TYPE(CLASS, PARENT) case Type::CLASS: \
335     print##CLASS##Before(cast<CLASS##Type>(T), OS); \
336     break;
337 #include "clang/AST/TypeNodes.inc"
338   }
339 
340   if (hasAfterQuals) {
341     if (NeedARCStrongQualifier) {
342       IncludeStrongLifetimeRAII Strong(Policy);
343       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
344     } else {
345       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
346     }
347   }
348 }
349 
350 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
351   SplitQualType split = splitAccordingToPolicy(t, Policy);
352   printAfter(split.Ty, split.Quals, OS);
353 }
354 
355 /// Prints the part of the type string after an identifier, e.g. for
356 /// "int foo[10]" it prints "[10]".
357 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
358   switch (T->getTypeClass()) {
359 #define ABSTRACT_TYPE(CLASS, PARENT)
360 #define TYPE(CLASS, PARENT) case Type::CLASS: \
361     print##CLASS##After(cast<CLASS##Type>(T), OS); \
362     break;
363 #include "clang/AST/TypeNodes.inc"
364   }
365 }
366 
367 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
368   OS << T->getName(Policy);
369   spaceBeforePlaceHolder(OS);
370 }
371 
372 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
373 
374 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
375   OS << "_Complex ";
376   printBefore(T->getElementType(), OS);
377 }
378 
379 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
380   printAfter(T->getElementType(), OS);
381 }
382 
383 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
384   IncludeStrongLifetimeRAII Strong(Policy);
385   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
386   printBefore(T->getPointeeType(), OS);
387   // Handle things like 'int (*A)[4];' correctly.
388   // FIXME: this should include vectors, but vectors use attributes I guess.
389   if (isa<ArrayType>(T->getPointeeType()))
390     OS << '(';
391   OS << '*';
392 }
393 
394 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
395   IncludeStrongLifetimeRAII Strong(Policy);
396   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
397   // Handle things like 'int (*A)[4];' correctly.
398   // FIXME: this should include vectors, but vectors use attributes I guess.
399   if (isa<ArrayType>(T->getPointeeType()))
400     OS << ')';
401   printAfter(T->getPointeeType(), OS);
402 }
403 
404 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
405                                           raw_ostream &OS) {
406   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
407   printBefore(T->getPointeeType(), OS);
408   OS << '^';
409 }
410 
411 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
412                                           raw_ostream &OS) {
413   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
414   printAfter(T->getPointeeType(), OS);
415 }
416 
417 // When printing a reference, the referenced type might also be a reference.
418 // If so, we want to skip that before printing the inner type.
419 static QualType skipTopLevelReferences(QualType T) {
420   if (auto *Ref = T->getAs<ReferenceType>())
421     return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
422   return T;
423 }
424 
425 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
426                                              raw_ostream &OS) {
427   IncludeStrongLifetimeRAII Strong(Policy);
428   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
429   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
430   printBefore(Inner, OS);
431   // Handle things like 'int (&A)[4];' correctly.
432   // FIXME: this should include vectors, but vectors use attributes I guess.
433   if (isa<ArrayType>(Inner))
434     OS << '(';
435   OS << '&';
436 }
437 
438 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
439                                             raw_ostream &OS) {
440   IncludeStrongLifetimeRAII Strong(Policy);
441   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
442   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
443   // Handle things like 'int (&A)[4];' correctly.
444   // FIXME: this should include vectors, but vectors use attributes I guess.
445   if (isa<ArrayType>(Inner))
446     OS << ')';
447   printAfter(Inner, OS);
448 }
449 
450 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
451                                              raw_ostream &OS) {
452   IncludeStrongLifetimeRAII Strong(Policy);
453   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
454   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
455   printBefore(Inner, OS);
456   // Handle things like 'int (&&A)[4];' correctly.
457   // FIXME: this should include vectors, but vectors use attributes I guess.
458   if (isa<ArrayType>(Inner))
459     OS << '(';
460   OS << "&&";
461 }
462 
463 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
464                                             raw_ostream &OS) {
465   IncludeStrongLifetimeRAII Strong(Policy);
466   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
467   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
468   // Handle things like 'int (&&A)[4];' correctly.
469   // FIXME: this should include vectors, but vectors use attributes I guess.
470   if (isa<ArrayType>(Inner))
471     OS << ')';
472   printAfter(Inner, OS);
473 }
474 
475 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
476                                            raw_ostream &OS) {
477   IncludeStrongLifetimeRAII Strong(Policy);
478   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
479   printBefore(T->getPointeeType(), OS);
480   // Handle things like 'int (Cls::*A)[4];' correctly.
481   // FIXME: this should include vectors, but vectors use attributes I guess.
482   if (isa<ArrayType>(T->getPointeeType()))
483     OS << '(';
484 
485   PrintingPolicy InnerPolicy(Policy);
486   InnerPolicy.IncludeTagDefinition = false;
487   TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
488 
489   OS << "::*";
490 }
491 
492 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
493                                           raw_ostream &OS) {
494   IncludeStrongLifetimeRAII Strong(Policy);
495   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
496   // Handle things like 'int (Cls::*A)[4];' correctly.
497   // FIXME: this should include vectors, but vectors use attributes I guess.
498   if (isa<ArrayType>(T->getPointeeType()))
499     OS << ')';
500   printAfter(T->getPointeeType(), OS);
501 }
502 
503 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
504                                            raw_ostream &OS) {
505   IncludeStrongLifetimeRAII Strong(Policy);
506   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
507   printBefore(T->getElementType(), OS);
508 }
509 
510 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
511                                           raw_ostream &OS) {
512   OS << '[';
513   if (T->getIndexTypeQualifiers().hasQualifiers()) {
514     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
515                        Policy.Restrict);
516     OS << ' ';
517   }
518 
519   if (T->getSizeModifier() == ArrayType::Static)
520     OS << "static ";
521 
522   OS << T->getSize().getZExtValue() << ']';
523   printAfter(T->getElementType(), OS);
524 }
525 
526 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
527                                              raw_ostream &OS) {
528   IncludeStrongLifetimeRAII Strong(Policy);
529   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
530   printBefore(T->getElementType(), OS);
531 }
532 
533 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
534                                             raw_ostream &OS) {
535   OS << "[]";
536   printAfter(T->getElementType(), OS);
537 }
538 
539 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
540                                            raw_ostream &OS) {
541   IncludeStrongLifetimeRAII Strong(Policy);
542   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
543   printBefore(T->getElementType(), OS);
544 }
545 
546 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
547                                           raw_ostream &OS) {
548   OS << '[';
549   if (T->getIndexTypeQualifiers().hasQualifiers()) {
550     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
551     OS << ' ';
552   }
553 
554   if (T->getSizeModifier() == VariableArrayType::Static)
555     OS << "static ";
556   else if (T->getSizeModifier() == VariableArrayType::Star)
557     OS << '*';
558 
559   if (T->getSizeExpr())
560     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
561   OS << ']';
562 
563   printAfter(T->getElementType(), OS);
564 }
565 
566 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
567   // Print the adjusted representation, otherwise the adjustment will be
568   // invisible.
569   printBefore(T->getAdjustedType(), OS);
570 }
571 
572 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
573   printAfter(T->getAdjustedType(), OS);
574 }
575 
576 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
577   // Print as though it's a pointer.
578   printAdjustedBefore(T, OS);
579 }
580 
581 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
582   printAdjustedAfter(T, OS);
583 }
584 
585 void TypePrinter::printDependentSizedArrayBefore(
586                                                const DependentSizedArrayType *T,
587                                                raw_ostream &OS) {
588   IncludeStrongLifetimeRAII Strong(Policy);
589   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
590   printBefore(T->getElementType(), OS);
591 }
592 
593 void TypePrinter::printDependentSizedArrayAfter(
594                                                const DependentSizedArrayType *T,
595                                                raw_ostream &OS) {
596   OS << '[';
597   if (T->getSizeExpr())
598     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
599   OS << ']';
600   printAfter(T->getElementType(), OS);
601 }
602 
603 void TypePrinter::printDependentAddressSpaceBefore(
604     const DependentAddressSpaceType *T, raw_ostream &OS) {
605   printBefore(T->getPointeeType(), OS);
606 }
607 
608 void TypePrinter::printDependentAddressSpaceAfter(
609     const DependentAddressSpaceType *T, raw_ostream &OS) {
610   OS << " __attribute__((address_space(";
611   if (T->getAddrSpaceExpr())
612     T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
613   OS << ")))";
614   printAfter(T->getPointeeType(), OS);
615 }
616 
617 void TypePrinter::printDependentSizedExtVectorBefore(
618                                           const DependentSizedExtVectorType *T,
619                                           raw_ostream &OS) {
620   printBefore(T->getElementType(), OS);
621 }
622 
623 void TypePrinter::printDependentSizedExtVectorAfter(
624                                           const DependentSizedExtVectorType *T,
625                                           raw_ostream &OS) {
626   OS << " __attribute__((ext_vector_type(";
627   if (T->getSizeExpr())
628     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
629   OS << ")))";
630   printAfter(T->getElementType(), OS);
631 }
632 
633 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
634   switch (T->getVectorKind()) {
635   case VectorType::AltiVecPixel:
636     OS << "__vector __pixel ";
637     break;
638   case VectorType::AltiVecBool:
639     OS << "__vector __bool ";
640     printBefore(T->getElementType(), OS);
641     break;
642   case VectorType::AltiVecVector:
643     OS << "__vector ";
644     printBefore(T->getElementType(), OS);
645     break;
646   case VectorType::NeonVector:
647     OS << "__attribute__((neon_vector_type("
648        << T->getNumElements() << "))) ";
649     printBefore(T->getElementType(), OS);
650     break;
651   case VectorType::NeonPolyVector:
652     OS << "__attribute__((neon_polyvector_type(" <<
653           T->getNumElements() << "))) ";
654     printBefore(T->getElementType(), OS);
655     break;
656   case VectorType::GenericVector: {
657     // FIXME: We prefer to print the size directly here, but have no way
658     // to get the size of the type.
659     OS << "__attribute__((__vector_size__("
660        << T->getNumElements()
661        << " * sizeof(";
662     print(T->getElementType(), OS, StringRef());
663     OS << ")))) ";
664     printBefore(T->getElementType(), OS);
665     break;
666   }
667   case VectorType::SveFixedLengthDataVector:
668   case VectorType::SveFixedLengthPredicateVector:
669     // FIXME: We prefer to print the size directly here, but have no way
670     // to get the size of the type.
671     OS << "__attribute__((__arm_sve_vector_bits__(";
672 
673     if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
674       // Predicates take a bit per byte of the vector size, multiply by 8 to
675       // get the number of bits passed to the attribute.
676       OS << T->getNumElements() * 8;
677     else
678       OS << T->getNumElements();
679 
680     OS << " * sizeof(";
681     print(T->getElementType(), OS, StringRef());
682     // Multiply by 8 for the number of bits.
683     OS << ") * 8))) ";
684     printBefore(T->getElementType(), OS);
685   }
686 }
687 
688 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
689   printAfter(T->getElementType(), OS);
690 }
691 
692 void TypePrinter::printDependentVectorBefore(
693     const DependentVectorType *T, raw_ostream &OS) {
694   switch (T->getVectorKind()) {
695   case VectorType::AltiVecPixel:
696     OS << "__vector __pixel ";
697     break;
698   case VectorType::AltiVecBool:
699     OS << "__vector __bool ";
700     printBefore(T->getElementType(), OS);
701     break;
702   case VectorType::AltiVecVector:
703     OS << "__vector ";
704     printBefore(T->getElementType(), OS);
705     break;
706   case VectorType::NeonVector:
707     OS << "__attribute__((neon_vector_type(";
708     if (T->getSizeExpr())
709       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
710     OS << "))) ";
711     printBefore(T->getElementType(), OS);
712     break;
713   case VectorType::NeonPolyVector:
714     OS << "__attribute__((neon_polyvector_type(";
715     if (T->getSizeExpr())
716       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
717     OS << "))) ";
718     printBefore(T->getElementType(), OS);
719     break;
720   case VectorType::GenericVector: {
721     // FIXME: We prefer to print the size directly here, but have no way
722     // to get the size of the type.
723     OS << "__attribute__((__vector_size__(";
724     if (T->getSizeExpr())
725       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
726     OS << " * sizeof(";
727     print(T->getElementType(), OS, StringRef());
728     OS << ")))) ";
729     printBefore(T->getElementType(), OS);
730     break;
731   }
732   case VectorType::SveFixedLengthDataVector:
733   case VectorType::SveFixedLengthPredicateVector:
734     // FIXME: We prefer to print the size directly here, but have no way
735     // to get the size of the type.
736     OS << "__attribute__((__arm_sve_vector_bits__(";
737     if (T->getSizeExpr()) {
738       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
739       if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
740         // Predicates take a bit per byte of the vector size, multiply by 8 to
741         // get the number of bits passed to the attribute.
742         OS << " * 8";
743       OS << " * sizeof(";
744       print(T->getElementType(), OS, StringRef());
745       // Multiply by 8 for the number of bits.
746       OS << ") * 8";
747     }
748     OS << "))) ";
749     printBefore(T->getElementType(), OS);
750   }
751 }
752 
753 void TypePrinter::printDependentVectorAfter(
754     const DependentVectorType *T, raw_ostream &OS) {
755   printAfter(T->getElementType(), OS);
756 }
757 
758 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
759                                        raw_ostream &OS) {
760   printBefore(T->getElementType(), OS);
761 }
762 
763 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
764   printAfter(T->getElementType(), OS);
765   OS << " __attribute__((ext_vector_type(";
766   OS << T->getNumElements();
767   OS << ")))";
768 }
769 
770 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T,
771                                             raw_ostream &OS) {
772   printBefore(T->getElementType(), OS);
773   OS << " __attribute__((matrix_type(";
774   OS << T->getNumRows() << ", " << T->getNumColumns();
775   OS << ")))";
776 }
777 
778 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T,
779                                            raw_ostream &OS) {
780   printAfter(T->getElementType(), OS);
781 }
782 
783 void TypePrinter::printDependentSizedMatrixBefore(
784     const DependentSizedMatrixType *T, raw_ostream &OS) {
785   printBefore(T->getElementType(), OS);
786   OS << " __attribute__((matrix_type(";
787   if (T->getRowExpr()) {
788     T->getRowExpr()->printPretty(OS, nullptr, Policy);
789   }
790   OS << ", ";
791   if (T->getColumnExpr()) {
792     T->getColumnExpr()->printPretty(OS, nullptr, Policy);
793   }
794   OS << ")))";
795 }
796 
797 void TypePrinter::printDependentSizedMatrixAfter(
798     const DependentSizedMatrixType *T, raw_ostream &OS) {
799   printAfter(T->getElementType(), OS);
800 }
801 
802 void
803 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
804                                                const PrintingPolicy &Policy)
805                                                                          const {
806   if (hasDynamicExceptionSpec()) {
807     OS << " throw(";
808     if (getExceptionSpecType() == EST_MSAny)
809       OS << "...";
810     else
811       for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
812         if (I)
813           OS << ", ";
814 
815         OS << getExceptionType(I).stream(Policy);
816       }
817     OS << ')';
818   } else if (EST_NoThrow == getExceptionSpecType()) {
819     OS << " __attribute__((nothrow))";
820   } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
821     OS << " noexcept";
822     // FIXME:Is it useful to print out the expression for a non-dependent
823     // noexcept specification?
824     if (isComputedNoexcept(getExceptionSpecType())) {
825       OS << '(';
826       if (getNoexceptExpr())
827         getNoexceptExpr()->printPretty(OS, nullptr, Policy);
828       OS << ')';
829     }
830   }
831 }
832 
833 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
834                                            raw_ostream &OS) {
835   if (T->hasTrailingReturn()) {
836     OS << "auto ";
837     if (!HasEmptyPlaceHolder)
838       OS << '(';
839   } else {
840     // If needed for precedence reasons, wrap the inner part in grouping parens.
841     SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
842     printBefore(T->getReturnType(), OS);
843     if (!PrevPHIsEmpty.get())
844       OS << '(';
845   }
846 }
847 
848 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
849   switch (ABI) {
850   case ParameterABI::Ordinary:
851     llvm_unreachable("asking for spelling of ordinary parameter ABI");
852   case ParameterABI::SwiftContext:
853     return "swift_context";
854   case ParameterABI::SwiftAsyncContext:
855     return "swift_async_context";
856   case ParameterABI::SwiftErrorResult:
857     return "swift_error_result";
858   case ParameterABI::SwiftIndirectResult:
859     return "swift_indirect_result";
860   }
861   llvm_unreachable("bad parameter ABI kind");
862 }
863 
864 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
865                                           raw_ostream &OS) {
866   // If needed for precedence reasons, wrap the inner part in grouping parens.
867   if (!HasEmptyPlaceHolder)
868     OS << ')';
869   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
870 
871   OS << '(';
872   {
873     ParamPolicyRAII ParamPolicy(Policy);
874     for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
875       if (i) OS << ", ";
876 
877       auto EPI = T->getExtParameterInfo(i);
878       if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
879       if (EPI.isNoEscape())
880         OS << "__attribute__((noescape)) ";
881       auto ABI = EPI.getABI();
882       if (ABI != ParameterABI::Ordinary)
883         OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
884 
885       print(T->getParamType(i), OS, StringRef());
886     }
887   }
888 
889   if (T->isVariadic()) {
890     if (T->getNumParams())
891       OS << ", ";
892     OS << "...";
893   } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
894     // Do not emit int() if we have a proto, emit 'int(void)'.
895     OS << "void";
896   }
897 
898   OS << ')';
899 
900   FunctionType::ExtInfo Info = T->getExtInfo();
901 
902   printFunctionAfter(Info, OS);
903 
904   if (!T->getMethodQuals().empty())
905     OS << " " << T->getMethodQuals().getAsString();
906 
907   switch (T->getRefQualifier()) {
908   case RQ_None:
909     break;
910 
911   case RQ_LValue:
912     OS << " &";
913     break;
914 
915   case RQ_RValue:
916     OS << " &&";
917     break;
918   }
919   T->printExceptionSpecification(OS, Policy);
920 
921   if (T->hasTrailingReturn()) {
922     OS << " -> ";
923     print(T->getReturnType(), OS, StringRef());
924   } else
925     printAfter(T->getReturnType(), OS);
926 }
927 
928 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
929                                      raw_ostream &OS) {
930   if (!InsideCCAttribute) {
931     switch (Info.getCC()) {
932     case CC_C:
933       // The C calling convention is the default on the vast majority of platforms
934       // we support.  If the user wrote it explicitly, it will usually be printed
935       // while traversing the AttributedType.  If the type has been desugared, let
936       // the canonical spelling be the implicit calling convention.
937       // FIXME: It would be better to be explicit in certain contexts, such as a
938       // cdecl function typedef used to declare a member function with the
939       // Microsoft C++ ABI.
940       break;
941     case CC_X86StdCall:
942       OS << " __attribute__((stdcall))";
943       break;
944     case CC_X86FastCall:
945       OS << " __attribute__((fastcall))";
946       break;
947     case CC_X86ThisCall:
948       OS << " __attribute__((thiscall))";
949       break;
950     case CC_X86VectorCall:
951       OS << " __attribute__((vectorcall))";
952       break;
953     case CC_X86Pascal:
954       OS << " __attribute__((pascal))";
955       break;
956     case CC_AAPCS:
957       OS << " __attribute__((pcs(\"aapcs\")))";
958       break;
959     case CC_AAPCS_VFP:
960       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
961       break;
962     case CC_AArch64VectorCall:
963       OS << "__attribute__((aarch64_vector_pcs))";
964       break;
965     case CC_IntelOclBicc:
966       OS << " __attribute__((intel_ocl_bicc))";
967       break;
968     case CC_Win64:
969       OS << " __attribute__((ms_abi))";
970       break;
971     case CC_X86_64SysV:
972       OS << " __attribute__((sysv_abi))";
973       break;
974     case CC_X86RegCall:
975       OS << " __attribute__((regcall))";
976       break;
977     case CC_SpirFunction:
978     case CC_OpenCLKernel:
979       // Do nothing. These CCs are not available as attributes.
980       break;
981     case CC_Swift:
982       OS << " __attribute__((swiftcall))";
983       break;
984     case CC_SwiftAsync:
985       OS << "__attribute__((swiftasynccall))";
986       break;
987     case CC_PreserveMost:
988       OS << " __attribute__((preserve_most))";
989       break;
990     case CC_PreserveAll:
991       OS << " __attribute__((preserve_all))";
992       break;
993     }
994   }
995 
996   if (Info.getNoReturn())
997     OS << " __attribute__((noreturn))";
998   if (Info.getCmseNSCall())
999     OS << " __attribute__((cmse_nonsecure_call))";
1000   if (Info.getProducesResult())
1001     OS << " __attribute__((ns_returns_retained))";
1002   if (Info.getRegParm())
1003     OS << " __attribute__((regparm ("
1004        << Info.getRegParm() << ")))";
1005   if (Info.getNoCallerSavedRegs())
1006     OS << " __attribute__((no_caller_saved_registers))";
1007   if (Info.getNoCfCheck())
1008     OS << " __attribute__((nocf_check))";
1009 }
1010 
1011 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
1012                                              raw_ostream &OS) {
1013   // If needed for precedence reasons, wrap the inner part in grouping parens.
1014   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
1015   printBefore(T->getReturnType(), OS);
1016   if (!PrevPHIsEmpty.get())
1017     OS << '(';
1018 }
1019 
1020 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
1021                                             raw_ostream &OS) {
1022   // If needed for precedence reasons, wrap the inner part in grouping parens.
1023   if (!HasEmptyPlaceHolder)
1024     OS << ')';
1025   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
1026 
1027   OS << "()";
1028   printFunctionAfter(T->getExtInfo(), OS);
1029   printAfter(T->getReturnType(), OS);
1030 }
1031 
1032 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
1033 
1034   // Compute the full nested-name-specifier for this type.
1035   // In C, this will always be empty except when the type
1036   // being printed is anonymous within other Record.
1037   if (!Policy.SuppressScope)
1038     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1039 
1040   IdentifierInfo *II = D->getIdentifier();
1041   OS << II->getName();
1042   spaceBeforePlaceHolder(OS);
1043 }
1044 
1045 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
1046                                              raw_ostream &OS) {
1047   printTypeSpec(T->getDecl(), OS);
1048 }
1049 
1050 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
1051                                             raw_ostream &OS) {}
1052 
1053 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
1054   printTypeSpec(T->getDecl(), OS);
1055 }
1056 
1057 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T,
1058                                             raw_ostream &OS) {
1059   StringRef MacroName = T->getMacroIdentifier()->getName();
1060   OS << MacroName << " ";
1061 
1062   // Since this type is meant to print the macro instead of the whole attribute,
1063   // we trim any attributes and go directly to the original modified type.
1064   printBefore(T->getModifiedType(), OS);
1065 }
1066 
1067 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T,
1068                                            raw_ostream &OS) {
1069   printAfter(T->getModifiedType(), OS);
1070 }
1071 
1072 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
1073 
1074 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
1075                                         raw_ostream &OS) {
1076   OS << "typeof ";
1077   if (T->getUnderlyingExpr())
1078     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1079   spaceBeforePlaceHolder(OS);
1080 }
1081 
1082 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
1083                                        raw_ostream &OS) {}
1084 
1085 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
1086   OS << "typeof(";
1087   print(T->getUnderlyingType(), OS, StringRef());
1088   OS << ')';
1089   spaceBeforePlaceHolder(OS);
1090 }
1091 
1092 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
1093 
1094 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
1095   OS << "decltype(";
1096   if (T->getUnderlyingExpr())
1097     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1098   OS << ')';
1099   spaceBeforePlaceHolder(OS);
1100 }
1101 
1102 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
1103 
1104 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
1105                                             raw_ostream &OS) {
1106   IncludeStrongLifetimeRAII Strong(Policy);
1107 
1108   switch (T->getUTTKind()) {
1109     case UnaryTransformType::EnumUnderlyingType:
1110       OS << "__underlying_type(";
1111       print(T->getBaseType(), OS, StringRef());
1112       OS << ')';
1113       spaceBeforePlaceHolder(OS);
1114       return;
1115   }
1116 
1117   printBefore(T->getBaseType(), OS);
1118 }
1119 
1120 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1121                                            raw_ostream &OS) {
1122   IncludeStrongLifetimeRAII Strong(Policy);
1123 
1124   switch (T->getUTTKind()) {
1125     case UnaryTransformType::EnumUnderlyingType:
1126       return;
1127   }
1128 
1129   printAfter(T->getBaseType(), OS);
1130 }
1131 
1132 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
1133   // If the type has been deduced, do not print 'auto'.
1134   if (!T->getDeducedType().isNull()) {
1135     printBefore(T->getDeducedType(), OS);
1136   } else {
1137     if (T->isConstrained()) {
1138       // FIXME: Track a TypeConstraint as type sugar, so that we can print the
1139       // type as it was written.
1140       T->getTypeConstraintConcept()->getDeclName().print(OS, Policy);
1141       auto Args = T->getTypeConstraintArguments();
1142       if (!Args.empty())
1143         printTemplateArgumentList(
1144             OS, Args, Policy,
1145             T->getTypeConstraintConcept()->getTemplateParameters());
1146       OS << ' ';
1147     }
1148     switch (T->getKeyword()) {
1149     case AutoTypeKeyword::Auto: OS << "auto"; break;
1150     case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
1151     case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
1152     }
1153     spaceBeforePlaceHolder(OS);
1154   }
1155 }
1156 
1157 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
1158   // If the type has been deduced, do not print 'auto'.
1159   if (!T->getDeducedType().isNull())
1160     printAfter(T->getDeducedType(), OS);
1161 }
1162 
1163 void TypePrinter::printDeducedTemplateSpecializationBefore(
1164     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1165   // If the type has been deduced, print the deduced type.
1166   if (!T->getDeducedType().isNull()) {
1167     printBefore(T->getDeducedType(), OS);
1168   } else {
1169     IncludeStrongLifetimeRAII Strong(Policy);
1170     T->getTemplateName().print(OS, Policy);
1171     spaceBeforePlaceHolder(OS);
1172   }
1173 }
1174 
1175 void TypePrinter::printDeducedTemplateSpecializationAfter(
1176     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1177   // If the type has been deduced, print the deduced type.
1178   if (!T->getDeducedType().isNull())
1179     printAfter(T->getDeducedType(), OS);
1180 }
1181 
1182 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1183   IncludeStrongLifetimeRAII Strong(Policy);
1184 
1185   OS << "_Atomic(";
1186   print(T->getValueType(), OS, StringRef());
1187   OS << ')';
1188   spaceBeforePlaceHolder(OS);
1189 }
1190 
1191 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1192 
1193 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1194   IncludeStrongLifetimeRAII Strong(Policy);
1195 
1196   if (T->isReadOnly())
1197     OS << "read_only ";
1198   else
1199     OS << "write_only ";
1200   OS << "pipe ";
1201   print(T->getElementType(), OS, StringRef());
1202   spaceBeforePlaceHolder(OS);
1203 }
1204 
1205 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1206 
1207 void TypePrinter::printExtIntBefore(const ExtIntType *T, raw_ostream &OS) {
1208   if (T->isUnsigned())
1209     OS << "unsigned ";
1210   OS << "_ExtInt(" << T->getNumBits() << ")";
1211   spaceBeforePlaceHolder(OS);
1212 }
1213 
1214 void TypePrinter::printExtIntAfter(const ExtIntType *T, raw_ostream &OS) {}
1215 
1216 void TypePrinter::printDependentExtIntBefore(const DependentExtIntType *T,
1217                                              raw_ostream &OS) {
1218   if (T->isUnsigned())
1219     OS << "unsigned ";
1220   OS << "_ExtInt(";
1221   T->getNumBitsExpr()->printPretty(OS, nullptr, Policy);
1222   OS << ")";
1223   spaceBeforePlaceHolder(OS);
1224 }
1225 
1226 void TypePrinter::printDependentExtIntAfter(const DependentExtIntType *T,
1227                                             raw_ostream &OS) {}
1228 
1229 /// Appends the given scope to the end of a string.
1230 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS,
1231                               DeclarationName NameInScope) {
1232   if (DC->isTranslationUnit())
1233     return;
1234 
1235   // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1236   // which can also print names for function and method scopes.
1237   if (DC->isFunctionOrMethod())
1238     return;
1239 
1240   if (Policy.Callbacks && Policy.Callbacks->isScopeVisible(DC))
1241     return;
1242 
1243   if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1244     if (Policy.SuppressUnwrittenScope && NS->isAnonymousNamespace())
1245       return AppendScope(DC->getParent(), OS, NameInScope);
1246 
1247     // Only suppress an inline namespace if the name has the same lookup
1248     // results in the enclosing namespace.
1249     if (Policy.SuppressInlineNamespace && NS->isInline() && NameInScope &&
1250         NS->isRedundantInlineQualifierFor(NameInScope))
1251       return AppendScope(DC->getParent(), OS, NameInScope);
1252 
1253     AppendScope(DC->getParent(), OS, NS->getDeclName());
1254     if (NS->getIdentifier())
1255       OS << NS->getName() << "::";
1256     else
1257       OS << "(anonymous namespace)::";
1258   } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1259     AppendScope(DC->getParent(), OS, Spec->getDeclName());
1260     IncludeStrongLifetimeRAII Strong(Policy);
1261     OS << Spec->getIdentifier()->getName();
1262     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1263     printTemplateArgumentList(
1264         OS, TemplateArgs.asArray(), Policy,
1265         Spec->getSpecializedTemplate()->getTemplateParameters());
1266     OS << "::";
1267   } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1268     AppendScope(DC->getParent(), OS, Tag->getDeclName());
1269     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1270       OS << Typedef->getIdentifier()->getName() << "::";
1271     else if (Tag->getIdentifier())
1272       OS << Tag->getIdentifier()->getName() << "::";
1273     else
1274       return;
1275   } else {
1276     AppendScope(DC->getParent(), OS, NameInScope);
1277   }
1278 }
1279 
1280 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1281   if (Policy.IncludeTagDefinition) {
1282     PrintingPolicy SubPolicy = Policy;
1283     SubPolicy.IncludeTagDefinition = false;
1284     D->print(OS, SubPolicy, Indentation);
1285     spaceBeforePlaceHolder(OS);
1286     return;
1287   }
1288 
1289   bool HasKindDecoration = false;
1290 
1291   // We don't print tags unless this is an elaborated type.
1292   // In C, we just assume every RecordType is an elaborated type.
1293   if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1294     HasKindDecoration = true;
1295     OS << D->getKindName();
1296     OS << ' ';
1297   }
1298 
1299   // Compute the full nested-name-specifier for this type.
1300   // In C, this will always be empty except when the type
1301   // being printed is anonymous within other Record.
1302   if (!Policy.SuppressScope)
1303     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1304 
1305   if (const IdentifierInfo *II = D->getIdentifier())
1306     OS << II->getName();
1307   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1308     assert(Typedef->getIdentifier() && "Typedef without identifier?");
1309     OS << Typedef->getIdentifier()->getName();
1310   } else {
1311     // Make an unambiguous representation for anonymous types, e.g.
1312     //   (anonymous enum at /usr/include/string.h:120:9)
1313     OS << (Policy.MSVCFormatting ? '`' : '(');
1314 
1315     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1316       OS << "lambda";
1317       HasKindDecoration = true;
1318     } else if ((isa<RecordDecl>(D) && cast<RecordDecl>(D)->isAnonymousStructOrUnion())) {
1319       OS << "anonymous";
1320     } else {
1321       OS << "unnamed";
1322     }
1323 
1324     if (Policy.AnonymousTagLocations) {
1325       // Suppress the redundant tag keyword if we just printed one.
1326       // We don't have to worry about ElaboratedTypes here because you can't
1327       // refer to an anonymous type with one.
1328       if (!HasKindDecoration)
1329         OS << " " << D->getKindName();
1330 
1331       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1332           D->getLocation());
1333       if (PLoc.isValid()) {
1334         OS << " at ";
1335         StringRef File = PLoc.getFilename();
1336         if (auto *Callbacks = Policy.Callbacks)
1337           OS << Callbacks->remapPath(File);
1338         else
1339           OS << File;
1340         OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
1341       }
1342     }
1343 
1344     OS << (Policy.MSVCFormatting ? '\'' : ')');
1345   }
1346 
1347   // If this is a class template specialization, print the template
1348   // arguments.
1349   if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1350     ArrayRef<TemplateArgument> Args;
1351     TypeSourceInfo *TAW = Spec->getTypeAsWritten();
1352     if (!Policy.PrintCanonicalTypes && TAW) {
1353       const TemplateSpecializationType *TST =
1354         cast<TemplateSpecializationType>(TAW->getType());
1355       Args = TST->template_arguments();
1356     } else {
1357       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1358       Args = TemplateArgs.asArray();
1359     }
1360     IncludeStrongLifetimeRAII Strong(Policy);
1361     printTemplateArgumentList(
1362         OS, Args, Policy,
1363         Spec->getSpecializedTemplate()->getTemplateParameters());
1364   }
1365 
1366   spaceBeforePlaceHolder(OS);
1367 }
1368 
1369 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1370   // Print the preferred name if we have one for this type.
1371   if (Policy.UsePreferredNames) {
1372     for (const auto *PNA : T->getDecl()->specific_attrs<PreferredNameAttr>()) {
1373       if (!declaresSameEntity(PNA->getTypedefType()->getAsCXXRecordDecl(),
1374                               T->getDecl()))
1375         continue;
1376       // Find the outermost typedef or alias template.
1377       QualType T = PNA->getTypedefType();
1378       while (true) {
1379         if (auto *TT = dyn_cast<TypedefType>(T))
1380           return printTypeSpec(TT->getDecl(), OS);
1381         if (auto *TST = dyn_cast<TemplateSpecializationType>(T))
1382           return printTemplateId(TST, OS, /*FullyQualify=*/true);
1383         T = T->getLocallyUnqualifiedSingleStepDesugaredType();
1384       }
1385     }
1386   }
1387 
1388   printTag(T->getDecl(), OS);
1389 }
1390 
1391 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1392 
1393 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1394   printTag(T->getDecl(), OS);
1395 }
1396 
1397 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1398 
1399 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1400                                               raw_ostream &OS) {
1401   TemplateTypeParmDecl *D = T->getDecl();
1402   if (D && D->isImplicit()) {
1403     if (auto *TC = D->getTypeConstraint()) {
1404       TC->print(OS, Policy);
1405       OS << ' ';
1406     }
1407     OS << "auto";
1408   } else if (IdentifierInfo *Id = T->getIdentifier())
1409     OS << Id->getName();
1410   else
1411     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1412 
1413   spaceBeforePlaceHolder(OS);
1414 }
1415 
1416 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1417                                              raw_ostream &OS) {}
1418 
1419 void TypePrinter::printSubstTemplateTypeParmBefore(
1420                                              const SubstTemplateTypeParmType *T,
1421                                              raw_ostream &OS) {
1422   IncludeStrongLifetimeRAII Strong(Policy);
1423   printBefore(T->getReplacementType(), OS);
1424 }
1425 
1426 void TypePrinter::printSubstTemplateTypeParmAfter(
1427                                              const SubstTemplateTypeParmType *T,
1428                                              raw_ostream &OS) {
1429   IncludeStrongLifetimeRAII Strong(Policy);
1430   printAfter(T->getReplacementType(), OS);
1431 }
1432 
1433 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1434                                         const SubstTemplateTypeParmPackType *T,
1435                                         raw_ostream &OS) {
1436   IncludeStrongLifetimeRAII Strong(Policy);
1437   printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1438 }
1439 
1440 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1441                                         const SubstTemplateTypeParmPackType *T,
1442                                         raw_ostream &OS) {
1443   IncludeStrongLifetimeRAII Strong(Policy);
1444   printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1445 }
1446 
1447 void TypePrinter::printTemplateId(const TemplateSpecializationType *T,
1448                                   raw_ostream &OS, bool FullyQualify) {
1449   IncludeStrongLifetimeRAII Strong(Policy);
1450 
1451   TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
1452   if (FullyQualify && TD) {
1453     if (!Policy.SuppressScope)
1454       AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
1455 
1456     IdentifierInfo *II = TD->getIdentifier();
1457     OS << II->getName();
1458   } else {
1459     T->getTemplateName().print(OS, Policy);
1460   }
1461 
1462   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1463   spaceBeforePlaceHolder(OS);
1464 }
1465 
1466 void TypePrinter::printTemplateSpecializationBefore(
1467                                             const TemplateSpecializationType *T,
1468                                             raw_ostream &OS) {
1469   printTemplateId(T, OS, Policy.FullyQualifiedName);
1470 }
1471 
1472 void TypePrinter::printTemplateSpecializationAfter(
1473                                             const TemplateSpecializationType *T,
1474                                             raw_ostream &OS) {}
1475 
1476 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1477                                                raw_ostream &OS) {
1478   if (Policy.PrintInjectedClassNameWithArguments)
1479     return printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1480 
1481   IncludeStrongLifetimeRAII Strong(Policy);
1482   T->getTemplateName().print(OS, Policy);
1483   spaceBeforePlaceHolder(OS);
1484 }
1485 
1486 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1487                                                raw_ostream &OS) {}
1488 
1489 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1490                                         raw_ostream &OS) {
1491   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
1492     TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
1493     assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
1494            "OwnedTagDecl expected to be a declaration for the type");
1495     PrintingPolicy SubPolicy = Policy;
1496     SubPolicy.IncludeTagDefinition = false;
1497     OwnedTagDecl->print(OS, SubPolicy, Indentation);
1498     spaceBeforePlaceHolder(OS);
1499     return;
1500   }
1501 
1502   // The tag definition will take care of these.
1503   if (!Policy.IncludeTagDefinition)
1504   {
1505     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1506     if (T->getKeyword() != ETK_None)
1507       OS << " ";
1508     NestedNameSpecifier *Qualifier = T->getQualifier();
1509     if (Qualifier)
1510       Qualifier->print(OS, Policy);
1511   }
1512 
1513   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1514   printBefore(T->getNamedType(), OS);
1515 }
1516 
1517 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1518                                         raw_ostream &OS) {
1519   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1520     return;
1521   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1522   printAfter(T->getNamedType(), OS);
1523 }
1524 
1525 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1526   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1527     printBefore(T->getInnerType(), OS);
1528     OS << '(';
1529   } else
1530     printBefore(T->getInnerType(), OS);
1531 }
1532 
1533 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1534   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1535     OS << ')';
1536     printAfter(T->getInnerType(), OS);
1537   } else
1538     printAfter(T->getInnerType(), OS);
1539 }
1540 
1541 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1542                                            raw_ostream &OS) {
1543   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1544   if (T->getKeyword() != ETK_None)
1545     OS << " ";
1546 
1547   T->getQualifier()->print(OS, Policy);
1548 
1549   OS << T->getIdentifier()->getName();
1550   spaceBeforePlaceHolder(OS);
1551 }
1552 
1553 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1554                                           raw_ostream &OS) {}
1555 
1556 void TypePrinter::printDependentTemplateSpecializationBefore(
1557         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1558   IncludeStrongLifetimeRAII Strong(Policy);
1559 
1560   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1561   if (T->getKeyword() != ETK_None)
1562     OS << " ";
1563 
1564   if (T->getQualifier())
1565     T->getQualifier()->print(OS, Policy);
1566   OS << "template " << T->getIdentifier()->getName();
1567   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1568   spaceBeforePlaceHolder(OS);
1569 }
1570 
1571 void TypePrinter::printDependentTemplateSpecializationAfter(
1572         const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1573 
1574 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1575                                            raw_ostream &OS) {
1576   printBefore(T->getPattern(), OS);
1577 }
1578 
1579 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1580                                           raw_ostream &OS) {
1581   printAfter(T->getPattern(), OS);
1582   OS << "...";
1583 }
1584 
1585 void TypePrinter::printAttributedBefore(const AttributedType *T,
1586                                         raw_ostream &OS) {
1587   // FIXME: Generate this with TableGen.
1588 
1589   // Prefer the macro forms of the GC and ownership qualifiers.
1590   if (T->getAttrKind() == attr::ObjCGC ||
1591       T->getAttrKind() == attr::ObjCOwnership)
1592     return printBefore(T->getEquivalentType(), OS);
1593 
1594   if (T->getAttrKind() == attr::ObjCKindOf)
1595     OS << "__kindof ";
1596 
1597   if (T->getAttrKind() == attr::AddressSpace)
1598     printBefore(T->getEquivalentType(), OS);
1599   else
1600     printBefore(T->getModifiedType(), OS);
1601 
1602   if (T->isMSTypeSpec()) {
1603     switch (T->getAttrKind()) {
1604     default: return;
1605     case attr::Ptr32: OS << " __ptr32"; break;
1606     case attr::Ptr64: OS << " __ptr64"; break;
1607     case attr::SPtr: OS << " __sptr"; break;
1608     case attr::UPtr: OS << " __uptr"; break;
1609     }
1610     spaceBeforePlaceHolder(OS);
1611   }
1612 
1613   // Print nullability type specifiers.
1614   if (T->getImmediateNullability()) {
1615     if (T->getAttrKind() == attr::TypeNonNull)
1616       OS << " _Nonnull";
1617     else if (T->getAttrKind() == attr::TypeNullable)
1618       OS << " _Nullable";
1619     else if (T->getAttrKind() == attr::TypeNullUnspecified)
1620       OS << " _Null_unspecified";
1621     else if (T->getAttrKind() == attr::TypeNullableResult)
1622       OS << " _Nullable_result";
1623     else
1624       llvm_unreachable("unhandled nullability");
1625     spaceBeforePlaceHolder(OS);
1626   }
1627 }
1628 
1629 void TypePrinter::printAttributedAfter(const AttributedType *T,
1630                                        raw_ostream &OS) {
1631   // FIXME: Generate this with TableGen.
1632 
1633   // Prefer the macro forms of the GC and ownership qualifiers.
1634   if (T->getAttrKind() == attr::ObjCGC ||
1635       T->getAttrKind() == attr::ObjCOwnership)
1636     return printAfter(T->getEquivalentType(), OS);
1637 
1638   // If this is a calling convention attribute, don't print the implicit CC from
1639   // the modified type.
1640   SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1641 
1642   printAfter(T->getModifiedType(), OS);
1643 
1644   // Some attributes are printed as qualifiers before the type, so we have
1645   // nothing left to do.
1646   if (T->getAttrKind() == attr::ObjCKindOf ||
1647       T->isMSTypeSpec() || T->getImmediateNullability())
1648     return;
1649 
1650   // Don't print the inert __unsafe_unretained attribute at all.
1651   if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
1652     return;
1653 
1654   // Don't print ns_returns_retained unless it had an effect.
1655   if (T->getAttrKind() == attr::NSReturnsRetained &&
1656       !T->getEquivalentType()->castAs<FunctionType>()
1657                              ->getExtInfo().getProducesResult())
1658     return;
1659 
1660   if (T->getAttrKind() == attr::LifetimeBound) {
1661     OS << " [[clang::lifetimebound]]";
1662     return;
1663   }
1664 
1665   // The printing of the address_space attribute is handled by the qualifier
1666   // since it is still stored in the qualifier. Return early to prevent printing
1667   // this twice.
1668   if (T->getAttrKind() == attr::AddressSpace)
1669     return;
1670 
1671   OS << " __attribute__((";
1672   switch (T->getAttrKind()) {
1673 #define TYPE_ATTR(NAME)
1674 #define DECL_OR_TYPE_ATTR(NAME)
1675 #define ATTR(NAME) case attr::NAME:
1676 #include "clang/Basic/AttrList.inc"
1677     llvm_unreachable("non-type attribute attached to type");
1678 
1679   case attr::OpenCLPrivateAddressSpace:
1680   case attr::OpenCLGlobalAddressSpace:
1681   case attr::OpenCLGlobalDeviceAddressSpace:
1682   case attr::OpenCLGlobalHostAddressSpace:
1683   case attr::OpenCLLocalAddressSpace:
1684   case attr::OpenCLConstantAddressSpace:
1685   case attr::OpenCLGenericAddressSpace:
1686     // FIXME: Update printAttributedBefore to print these once we generate
1687     // AttributedType nodes for them.
1688     break;
1689 
1690   case attr::LifetimeBound:
1691   case attr::TypeNonNull:
1692   case attr::TypeNullable:
1693   case attr::TypeNullableResult:
1694   case attr::TypeNullUnspecified:
1695   case attr::ObjCGC:
1696   case attr::ObjCInertUnsafeUnretained:
1697   case attr::ObjCKindOf:
1698   case attr::ObjCOwnership:
1699   case attr::Ptr32:
1700   case attr::Ptr64:
1701   case attr::SPtr:
1702   case attr::UPtr:
1703   case attr::AddressSpace:
1704   case attr::CmseNSCall:
1705     llvm_unreachable("This attribute should have been handled already");
1706 
1707   case attr::NSReturnsRetained:
1708     OS << "ns_returns_retained";
1709     break;
1710 
1711   // FIXME: When Sema learns to form this AttributedType, avoid printing the
1712   // attribute again in printFunctionProtoAfter.
1713   case attr::AnyX86NoCfCheck: OS << "nocf_check"; break;
1714   case attr::CDecl: OS << "cdecl"; break;
1715   case attr::FastCall: OS << "fastcall"; break;
1716   case attr::StdCall: OS << "stdcall"; break;
1717   case attr::ThisCall: OS << "thiscall"; break;
1718   case attr::SwiftCall: OS << "swiftcall"; break;
1719   case attr::SwiftAsyncCall: OS << "swiftasynccall"; break;
1720   case attr::VectorCall: OS << "vectorcall"; break;
1721   case attr::Pascal: OS << "pascal"; break;
1722   case attr::MSABI: OS << "ms_abi"; break;
1723   case attr::SysVABI: OS << "sysv_abi"; break;
1724   case attr::RegCall: OS << "regcall"; break;
1725   case attr::Pcs: {
1726     OS << "pcs(";
1727    QualType t = T->getEquivalentType();
1728    while (!t->isFunctionType())
1729      t = t->getPointeeType();
1730    OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1731          "\"aapcs\"" : "\"aapcs-vfp\"");
1732    OS << ')';
1733    break;
1734   }
1735   case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
1736   case attr::IntelOclBicc: OS << "inteloclbicc"; break;
1737   case attr::PreserveMost:
1738     OS << "preserve_most";
1739     break;
1740 
1741   case attr::PreserveAll:
1742     OS << "preserve_all";
1743     break;
1744   case attr::NoDeref:
1745     OS << "noderef";
1746     break;
1747   case attr::AcquireHandle:
1748     OS << "acquire_handle";
1749     break;
1750   case attr::ArmMveStrictPolymorphism:
1751     OS << "__clang_arm_mve_strict_polymorphism";
1752     break;
1753   }
1754   OS << "))";
1755 }
1756 
1757 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1758                                            raw_ostream &OS) {
1759   OS << T->getDecl()->getName();
1760   spaceBeforePlaceHolder(OS);
1761 }
1762 
1763 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1764                                           raw_ostream &OS) {}
1765 
1766 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1767                                           raw_ostream &OS) {
1768   OS << T->getDecl()->getName();
1769   if (!T->qual_empty()) {
1770     bool isFirst = true;
1771     OS << '<';
1772     for (const auto *I : T->quals()) {
1773       if (isFirst)
1774         isFirst = false;
1775       else
1776         OS << ',';
1777       OS << I->getName();
1778     }
1779     OS << '>';
1780   }
1781 
1782   spaceBeforePlaceHolder(OS);
1783 }
1784 
1785 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1786                                           raw_ostream &OS) {}
1787 
1788 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1789                                         raw_ostream &OS) {
1790   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1791       !T->isKindOfTypeAsWritten())
1792     return printBefore(T->getBaseType(), OS);
1793 
1794   if (T->isKindOfTypeAsWritten())
1795     OS << "__kindof ";
1796 
1797   print(T->getBaseType(), OS, StringRef());
1798 
1799   if (T->isSpecializedAsWritten()) {
1800     bool isFirst = true;
1801     OS << '<';
1802     for (auto typeArg : T->getTypeArgsAsWritten()) {
1803       if (isFirst)
1804         isFirst = false;
1805       else
1806         OS << ",";
1807 
1808       print(typeArg, OS, StringRef());
1809     }
1810     OS << '>';
1811   }
1812 
1813   if (!T->qual_empty()) {
1814     bool isFirst = true;
1815     OS << '<';
1816     for (const auto *I : T->quals()) {
1817       if (isFirst)
1818         isFirst = false;
1819       else
1820         OS << ',';
1821       OS << I->getName();
1822     }
1823     OS << '>';
1824   }
1825 
1826   spaceBeforePlaceHolder(OS);
1827 }
1828 
1829 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1830                                         raw_ostream &OS) {
1831   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1832       !T->isKindOfTypeAsWritten())
1833     return printAfter(T->getBaseType(), OS);
1834 }
1835 
1836 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1837                                                raw_ostream &OS) {
1838   printBefore(T->getPointeeType(), OS);
1839 
1840   // If we need to print the pointer, print it now.
1841   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1842       !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1843     if (HasEmptyPlaceHolder)
1844       OS << ' ';
1845     OS << '*';
1846   }
1847 }
1848 
1849 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1850                                               raw_ostream &OS) {}
1851 
1852 static
1853 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1854 
1855 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1856   return A.getArgument();
1857 }
1858 
1859 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP,
1860                           llvm::raw_ostream &OS, bool IncludeType) {
1861   A.print(PP, OS, IncludeType);
1862 }
1863 
1864 static void printArgument(const TemplateArgumentLoc &A,
1865                           const PrintingPolicy &PP, llvm::raw_ostream &OS,
1866                           bool IncludeType) {
1867   const TemplateArgument::ArgKind &Kind = A.getArgument().getKind();
1868   if (Kind == TemplateArgument::ArgKind::Type)
1869     return A.getTypeSourceInfo()->getType().print(OS, PP);
1870   return A.getArgument().print(PP, OS, IncludeType);
1871 }
1872 
1873 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
1874                                           TemplateArgument Pattern,
1875                                           ArrayRef<TemplateArgument> Args,
1876                                           unsigned Depth);
1877 
1878 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern,
1879                               ArrayRef<TemplateArgument> Args, unsigned Depth) {
1880   if (Ctx.hasSameType(T, Pattern))
1881     return true;
1882 
1883   // A type parameter matches its argument.
1884   if (auto *TTPT = Pattern->getAs<TemplateTypeParmType>()) {
1885     if (TTPT->getDepth() == Depth && TTPT->getIndex() < Args.size() &&
1886         Args[TTPT->getIndex()].getKind() == TemplateArgument::Type) {
1887       QualType SubstArg = Ctx.getQualifiedType(
1888           Args[TTPT->getIndex()].getAsType(), Pattern.getQualifiers());
1889       return Ctx.hasSameType(SubstArg, T);
1890     }
1891     return false;
1892   }
1893 
1894   // FIXME: Recurse into array types.
1895 
1896   // All other cases will need the types to be identically qualified.
1897   Qualifiers TQual, PatQual;
1898   T = Ctx.getUnqualifiedArrayType(T, TQual);
1899   Pattern = Ctx.getUnqualifiedArrayType(Pattern, PatQual);
1900   if (TQual != PatQual)
1901     return false;
1902 
1903   // Recurse into pointer-like types.
1904   {
1905     QualType TPointee = T->getPointeeType();
1906     QualType PPointee = Pattern->getPointeeType();
1907     if (!TPointee.isNull() && !PPointee.isNull())
1908       return T->getTypeClass() == Pattern->getTypeClass() &&
1909              isSubstitutedType(Ctx, TPointee, PPointee, Args, Depth);
1910   }
1911 
1912   // Recurse into template specialization types.
1913   if (auto *PTST =
1914           Pattern.getCanonicalType()->getAs<TemplateSpecializationType>()) {
1915     TemplateName Template;
1916     ArrayRef<TemplateArgument> TemplateArgs;
1917     if (auto *TTST = T->getAs<TemplateSpecializationType>()) {
1918       Template = TTST->getTemplateName();
1919       TemplateArgs = TTST->template_arguments();
1920     } else if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1921                    T->getAsCXXRecordDecl())) {
1922       Template = TemplateName(CTSD->getSpecializedTemplate());
1923       TemplateArgs = CTSD->getTemplateArgs().asArray();
1924     } else {
1925       return false;
1926     }
1927 
1928     if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(),
1929                                        Args, Depth))
1930       return false;
1931     if (TemplateArgs.size() != PTST->getNumArgs())
1932       return false;
1933     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1934       if (!isSubstitutedTemplateArgument(Ctx, TemplateArgs[I], PTST->getArg(I),
1935                                          Args, Depth))
1936         return false;
1937     return true;
1938   }
1939 
1940   // FIXME: Handle more cases.
1941   return false;
1942 }
1943 
1944 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
1945                                           TemplateArgument Pattern,
1946                                           ArrayRef<TemplateArgument> Args,
1947                                           unsigned Depth) {
1948   Arg = Ctx.getCanonicalTemplateArgument(Arg);
1949   Pattern = Ctx.getCanonicalTemplateArgument(Pattern);
1950   if (Arg.structurallyEquals(Pattern))
1951     return true;
1952 
1953   if (Pattern.getKind() == TemplateArgument::Expression) {
1954     if (auto *DRE =
1955             dyn_cast<DeclRefExpr>(Pattern.getAsExpr()->IgnoreParenImpCasts())) {
1956       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
1957         return NTTP->getDepth() == Depth && Args.size() > NTTP->getIndex() &&
1958                Args[NTTP->getIndex()].structurallyEquals(Arg);
1959     }
1960   }
1961 
1962   if (Arg.getKind() != Pattern.getKind())
1963     return false;
1964 
1965   if (Arg.getKind() == TemplateArgument::Type)
1966     return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args,
1967                              Depth);
1968 
1969   if (Arg.getKind() == TemplateArgument::Template) {
1970     TemplateDecl *PatTD = Pattern.getAsTemplate().getAsTemplateDecl();
1971     if (auto *TTPD = dyn_cast_or_null<TemplateTemplateParmDecl>(PatTD))
1972       return TTPD->getDepth() == Depth && Args.size() > TTPD->getIndex() &&
1973              Ctx.getCanonicalTemplateArgument(Args[TTPD->getIndex()])
1974                  .structurallyEquals(Arg);
1975   }
1976 
1977   // FIXME: Handle more cases.
1978   return false;
1979 }
1980 
1981 /// Make a best-effort determination of whether the type T can be produced by
1982 /// substituting Args into the default argument of Param.
1983 static bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg,
1984                                          const NamedDecl *Param,
1985                                          ArrayRef<TemplateArgument> Args,
1986                                          unsigned Depth) {
1987   // An empty pack is equivalent to not providing a pack argument.
1988   if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0)
1989     return true;
1990 
1991   if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) {
1992     return TTPD->hasDefaultArgument() &&
1993            isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(),
1994                                          Args, Depth);
1995   } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
1996     return TTPD->hasDefaultArgument() &&
1997            isSubstitutedTemplateArgument(
1998                Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth);
1999   } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2000     return NTTPD->hasDefaultArgument() &&
2001            isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(),
2002                                          Args, Depth);
2003   }
2004   return false;
2005 }
2006 
2007 template <typename TA>
2008 static void
2009 printTo(raw_ostream &OS, ArrayRef<TA> Args, const PrintingPolicy &Policy,
2010         const TemplateParameterList *TPL, bool IsPack, unsigned ParmIndex) {
2011   // Drop trailing template arguments that match default arguments.
2012   if (TPL && Policy.SuppressDefaultTemplateArgs &&
2013       !Policy.PrintCanonicalTypes && !Args.empty() && !IsPack &&
2014       Args.size() <= TPL->size()) {
2015     ASTContext &Ctx = TPL->getParam(0)->getASTContext();
2016     llvm::SmallVector<TemplateArgument, 8> OrigArgs;
2017     for (const TA &A : Args)
2018       OrigArgs.push_back(getArgument(A));
2019     while (!Args.empty() &&
2020            isSubstitutedDefaultArgument(Ctx, getArgument(Args.back()),
2021                                         TPL->getParam(Args.size() - 1),
2022                                         OrigArgs, TPL->getDepth()))
2023       Args = Args.drop_back();
2024   }
2025 
2026   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
2027   if (!IsPack)
2028     OS << '<';
2029 
2030   bool NeedSpace = false;
2031   bool FirstArg = true;
2032   for (const auto &Arg : Args) {
2033     // Print the argument into a string.
2034     SmallString<128> Buf;
2035     llvm::raw_svector_ostream ArgOS(Buf);
2036     const TemplateArgument &Argument = getArgument(Arg);
2037     if (Argument.getKind() == TemplateArgument::Pack) {
2038       if (Argument.pack_size() && !FirstArg)
2039         OS << Comma;
2040       printTo(ArgOS, Argument.getPackAsArray(), Policy, TPL,
2041               /*IsPack*/ true, ParmIndex);
2042     } else {
2043       if (!FirstArg)
2044         OS << Comma;
2045       // Tries to print the argument with location info if exists.
2046       printArgument(
2047           Arg, Policy, ArgOS,
2048           TemplateParameterList::shouldIncludeTypeForArgument(TPL, ParmIndex));
2049     }
2050     StringRef ArgString = ArgOS.str();
2051 
2052     // If this is the first argument and its string representation
2053     // begins with the global scope specifier ('::foo'), add a space
2054     // to avoid printing the diagraph '<:'.
2055     if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
2056       OS << ' ';
2057 
2058     OS << ArgString;
2059 
2060     // If the last character of our string is '>', add another space to
2061     // keep the two '>''s separate tokens.
2062     if (!ArgString.empty()) {
2063       NeedSpace = Policy.SplitTemplateClosers && ArgString.back() == '>';
2064       FirstArg = false;
2065     }
2066 
2067     // Use same template parameter for all elements of Pack
2068     if (!IsPack)
2069       ParmIndex++;
2070   }
2071 
2072   if (!IsPack) {
2073     if (NeedSpace)
2074       OS << ' ';
2075     OS << '>';
2076   }
2077 }
2078 
2079 void clang::printTemplateArgumentList(raw_ostream &OS,
2080                                       const TemplateArgumentListInfo &Args,
2081                                       const PrintingPolicy &Policy,
2082                                       const TemplateParameterList *TPL) {
2083   printTemplateArgumentList(OS, Args.arguments(), Policy, TPL);
2084 }
2085 
2086 void clang::printTemplateArgumentList(raw_ostream &OS,
2087                                       ArrayRef<TemplateArgument> Args,
2088                                       const PrintingPolicy &Policy,
2089                                       const TemplateParameterList *TPL) {
2090   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2091 }
2092 
2093 void clang::printTemplateArgumentList(raw_ostream &OS,
2094                                       ArrayRef<TemplateArgumentLoc> Args,
2095                                       const PrintingPolicy &Policy,
2096                                       const TemplateParameterList *TPL) {
2097   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2098 }
2099 
2100 std::string Qualifiers::getAsString() const {
2101   LangOptions LO;
2102   return getAsString(PrintingPolicy(LO));
2103 }
2104 
2105 // Appends qualifiers to the given string, separated by spaces.  Will
2106 // prefix a space if the string is non-empty.  Will not append a final
2107 // space.
2108 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
2109   SmallString<64> Buf;
2110   llvm::raw_svector_ostream StrOS(Buf);
2111   print(StrOS, Policy);
2112   return std::string(StrOS.str());
2113 }
2114 
2115 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
2116   if (getCVRQualifiers())
2117     return false;
2118 
2119   if (getAddressSpace() != LangAS::Default)
2120     return false;
2121 
2122   if (getObjCGCAttr())
2123     return false;
2124 
2125   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
2126     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
2127       return false;
2128 
2129   return true;
2130 }
2131 
2132 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) {
2133   switch (AS) {
2134   case LangAS::Default:
2135     return "";
2136   case LangAS::opencl_global:
2137   case LangAS::sycl_global:
2138     return "__global";
2139   case LangAS::opencl_local:
2140   case LangAS::sycl_local:
2141     return "__local";
2142   case LangAS::opencl_private:
2143   case LangAS::sycl_private:
2144     return "__private";
2145   case LangAS::opencl_constant:
2146     return "__constant";
2147   case LangAS::opencl_generic:
2148     return "__generic";
2149   case LangAS::opencl_global_device:
2150   case LangAS::sycl_global_device:
2151     return "__global_device";
2152   case LangAS::opencl_global_host:
2153   case LangAS::sycl_global_host:
2154     return "__global_host";
2155   case LangAS::cuda_device:
2156     return "__device__";
2157   case LangAS::cuda_constant:
2158     return "__constant__";
2159   case LangAS::cuda_shared:
2160     return "__shared__";
2161   case LangAS::ptr32_sptr:
2162     return "__sptr __ptr32";
2163   case LangAS::ptr32_uptr:
2164     return "__uptr __ptr32";
2165   case LangAS::ptr64:
2166     return "__ptr64";
2167   default:
2168     return std::to_string(toTargetAddressSpace(AS));
2169   }
2170 }
2171 
2172 // Appends qualifiers to the given string, separated by spaces.  Will
2173 // prefix a space if the string is non-empty.  Will not append a final
2174 // space.
2175 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
2176                        bool appendSpaceIfNonEmpty) const {
2177   bool addSpace = false;
2178 
2179   unsigned quals = getCVRQualifiers();
2180   if (quals) {
2181     AppendTypeQualList(OS, quals, Policy.Restrict);
2182     addSpace = true;
2183   }
2184   if (hasUnaligned()) {
2185     if (addSpace)
2186       OS << ' ';
2187     OS << "__unaligned";
2188     addSpace = true;
2189   }
2190   auto ASStr = getAddrSpaceAsString(getAddressSpace());
2191   if (!ASStr.empty()) {
2192     if (addSpace)
2193       OS << ' ';
2194     addSpace = true;
2195     // Wrap target address space into an attribute syntax
2196     if (isTargetAddressSpace(getAddressSpace()))
2197       OS << "__attribute__((address_space(" << ASStr << ")))";
2198     else
2199       OS << ASStr;
2200   }
2201 
2202   if (Qualifiers::GC gc = getObjCGCAttr()) {
2203     if (addSpace)
2204       OS << ' ';
2205     addSpace = true;
2206     if (gc == Qualifiers::Weak)
2207       OS << "__weak";
2208     else
2209       OS << "__strong";
2210   }
2211   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
2212     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
2213       if (addSpace)
2214         OS << ' ';
2215       addSpace = true;
2216     }
2217 
2218     switch (lifetime) {
2219     case Qualifiers::OCL_None: llvm_unreachable("none but true");
2220     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
2221     case Qualifiers::OCL_Strong:
2222       if (!Policy.SuppressStrongLifetime)
2223         OS << "__strong";
2224       break;
2225 
2226     case Qualifiers::OCL_Weak: OS << "__weak"; break;
2227     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
2228     }
2229   }
2230 
2231   if (appendSpaceIfNonEmpty && addSpace)
2232     OS << ' ';
2233 }
2234 
2235 std::string QualType::getAsString() const {
2236   return getAsString(split(), LangOptions());
2237 }
2238 
2239 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
2240   std::string S;
2241   getAsStringInternal(S, Policy);
2242   return S;
2243 }
2244 
2245 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
2246                                   const PrintingPolicy &Policy) {
2247   std::string buffer;
2248   getAsStringInternal(ty, qs, buffer, Policy);
2249   return buffer;
2250 }
2251 
2252 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy,
2253                      const Twine &PlaceHolder, unsigned Indentation) const {
2254   print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder,
2255         Indentation);
2256 }
2257 
2258 void QualType::print(const Type *ty, Qualifiers qs,
2259                      raw_ostream &OS, const PrintingPolicy &policy,
2260                      const Twine &PlaceHolder, unsigned Indentation) {
2261   SmallString<128> PHBuf;
2262   StringRef PH = PlaceHolder.toStringRef(PHBuf);
2263 
2264   TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
2265 }
2266 
2267 void QualType::getAsStringInternal(std::string &Str,
2268                                    const PrintingPolicy &Policy) const {
2269   return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str,
2270                              Policy);
2271 }
2272 
2273 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
2274                                    std::string &buffer,
2275                                    const PrintingPolicy &policy) {
2276   SmallString<256> Buf;
2277   llvm::raw_svector_ostream StrOS(Buf);
2278   TypePrinter(policy).print(ty, qs, StrOS, buffer);
2279   std::string str = std::string(StrOS.str());
2280   buffer.swap(str);
2281 }
2282