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