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