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