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