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