1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code to print types from Clang's type system.
11 //===----------------------------------------------------------------------===//
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"
48 using namespace clang
;
52 /// RAII object that enables printing of the ARC __strong lifetime
54 class IncludeStrongLifetimeRAII
{
55 PrintingPolicy
&Policy
;
59 explicit IncludeStrongLifetimeRAII(PrintingPolicy
&Policy
)
60 : Policy(Policy
), Old(Policy
.SuppressStrongLifetime
) {
61 if (!Policy
.SuppressLifetimeQualifiers
)
62 Policy
.SuppressStrongLifetime
= false;
65 ~IncludeStrongLifetimeRAII() { Policy
.SuppressStrongLifetime
= Old
; }
68 class ParamPolicyRAII
{
69 PrintingPolicy
&Policy
;
73 explicit ParamPolicyRAII(PrintingPolicy
&Policy
)
74 : Policy(Policy
), Old(Policy
.SuppressSpecifiers
) {
75 Policy
.SuppressSpecifiers
= false;
78 ~ParamPolicyRAII() { Policy
.SuppressSpecifiers
= Old
; }
81 class DefaultTemplateArgsPolicyRAII
{
82 PrintingPolicy
&Policy
;
86 explicit DefaultTemplateArgsPolicyRAII(PrintingPolicy
&Policy
)
87 : Policy(Policy
), Old(Policy
.SuppressDefaultTemplateArgs
) {
88 Policy
.SuppressDefaultTemplateArgs
= false;
91 ~DefaultTemplateArgsPolicyRAII() { Policy
.SuppressDefaultTemplateArgs
= Old
; }
94 class ElaboratedTypePolicyRAII
{
95 PrintingPolicy
&Policy
;
96 bool SuppressTagKeyword
;
100 explicit ElaboratedTypePolicyRAII(PrintingPolicy
&Policy
) : Policy(Policy
) {
101 SuppressTagKeyword
= Policy
.SuppressTagKeyword
;
102 SuppressScope
= Policy
.SuppressScope
;
103 Policy
.SuppressTagKeyword
= true;
104 Policy
.SuppressScope
= true;
107 ~ElaboratedTypePolicyRAII() {
108 Policy
.SuppressTagKeyword
= SuppressTagKeyword
;
109 Policy
.SuppressScope
= SuppressScope
;
114 PrintingPolicy Policy
;
115 unsigned Indentation
;
116 bool HasEmptyPlaceHolder
= false;
117 bool InsideCCAttribute
= false;
120 explicit TypePrinter(const PrintingPolicy
&Policy
, unsigned Indentation
= 0)
121 : Policy(Policy
), Indentation(Indentation
) {}
123 void print(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
,
124 StringRef PlaceHolder
);
125 void print(QualType T
, raw_ostream
&OS
, StringRef PlaceHolder
);
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
,
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"
146 void printBefore(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
);
147 void printAfter(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
);
152 static void AppendTypeQualList(raw_ostream
&OS
, unsigned TypeQuals
,
153 bool HasRestrictKeyword
) {
154 bool appendSpace
= false;
155 if (TypeQuals
& Qualifiers::Const
) {
159 if (TypeQuals
& Qualifiers::Volatile
) {
160 if (appendSpace
) OS
<< ' ';
164 if (TypeQuals
& Qualifiers::Restrict
) {
165 if (appendSpace
) OS
<< ' ';
166 if (HasRestrictKeyword
) {
174 void TypePrinter::spaceBeforePlaceHolder(raw_ostream
&OS
) {
175 if (!HasEmptyPlaceHolder
)
179 static SplitQualType
splitAccordingToPolicy(QualType QT
,
180 const PrintingPolicy
&Policy
) {
181 if (Policy
.PrintCanonicalTypes
)
182 QT
= QT
.getCanonicalType();
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
);
191 void TypePrinter::print(const Type
*T
, Qualifiers Quals
, raw_ostream
&OS
,
192 StringRef PlaceHolder
) {
198 SaveAndRestore
PHVal(HasEmptyPlaceHolder
, PlaceHolder
.empty());
200 printBefore(T
, Quals
, OS
);
202 printAfter(T
, Quals
, OS
);
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();
225 case Type::UnresolvedUsing
:
228 case Type::TypeOfExpr
:
231 case Type::UnaryTransform
:
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
:
248 case Type::DependentBitInt
:
249 case Type::BTFTagAttributed
:
250 CanPrefixQualifiers
= true;
253 case Type::ObjCObjectPointer
:
254 CanPrefixQualifiers
= T
->isObjCIdType() || T
->isObjCClassType() ||
255 T
->isObjCQualifiedIdType() || T
->isObjCQualifiedClassType();
258 case Type::VariableArray
:
259 case Type::DependentSizedArray
:
260 NeedARCStrongQualifier
= true;
263 case Type::ConstantArray
:
264 case Type::IncompleteArray
:
265 return canPrefixQualifiers(
266 cast
<ArrayType
>(UnderlyingType
)->getElementType().getTypePtr(),
267 NeedARCStrongQualifier
);
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
:
280 case Type::ExtVector
:
281 case Type::ConstantMatrix
:
282 case Type::DependentSizedMatrix
:
283 case Type::FunctionProto
:
284 case Type::FunctionNoProto
:
286 case Type::PackExpansion
:
287 case Type::SubstTemplateTypeParm
:
288 case Type::MacroQualified
:
289 CanPrefixQualifiers
= false;
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
;
301 return CanPrefixQualifiers
;
304 void TypePrinter::printBefore(QualType T
, raw_ostream
&OS
) {
305 SplitQualType Split
= splitAccordingToPolicy(T
, Policy
);
307 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
309 Qualifiers Quals
= Split
.Quals
;
310 if (const auto *Subst
= dyn_cast
<SubstTemplateTypeParmType
>(Split
.Ty
))
311 Quals
-= QualType(Subst
, 0).getQualifiers();
313 printBefore(Split
.Ty
, Quals
, OS
);
316 /// Prints the part of the type string before an identifier, e.g. for
317 /// "int foo[10]" it prints "int ".
318 void TypePrinter::printBefore(const Type
*T
,Qualifiers Quals
, raw_ostream
&OS
) {
319 if (Policy
.SuppressSpecifiers
&& T
->isSpecifierType())
322 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
);
324 // Print qualifiers as appropriate.
326 bool CanPrefixQualifiers
= false;
327 bool NeedARCStrongQualifier
= false;
328 CanPrefixQualifiers
= canPrefixQualifiers(T
, NeedARCStrongQualifier
);
330 if (CanPrefixQualifiers
&& !Quals
.empty()) {
331 if (NeedARCStrongQualifier
) {
332 IncludeStrongLifetimeRAII
Strong(Policy
);
333 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/true);
335 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/true);
339 bool hasAfterQuals
= false;
340 if (!CanPrefixQualifiers
&& !Quals
.empty()) {
341 hasAfterQuals
= !Quals
.isEmptyWhenPrinted(Policy
);
343 HasEmptyPlaceHolder
= false;
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); \
351 #include "clang/AST/TypeNodes.inc"
355 if (NeedARCStrongQualifier
) {
356 IncludeStrongLifetimeRAII
Strong(Policy
);
357 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty
.get());
359 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty
.get());
364 void TypePrinter::printAfter(QualType t
, raw_ostream
&OS
) {
365 SplitQualType split
= splitAccordingToPolicy(t
, Policy
);
366 printAfter(split
.Ty
, split
.Quals
, OS
);
369 /// Prints the part of the type string after an identifier, e.g. for
370 /// "int foo[10]" it prints "[10]".
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); \
377 #include "clang/AST/TypeNodes.inc"
381 void TypePrinter::printBuiltinBefore(const BuiltinType
*T
, raw_ostream
&OS
) {
382 OS
<< T
->getName(Policy
);
383 spaceBeforePlaceHolder(OS
);
386 void TypePrinter::printBuiltinAfter(const BuiltinType
*T
, raw_ostream
&OS
) {}
388 void TypePrinter::printComplexBefore(const ComplexType
*T
, raw_ostream
&OS
) {
390 printBefore(T
->getElementType(), OS
);
393 void TypePrinter::printComplexAfter(const ComplexType
*T
, raw_ostream
&OS
) {
394 printAfter(T
->getElementType(), 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()))
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()))
415 printAfter(T
->getPointeeType(), OS
);
418 void TypePrinter::printBlockPointerBefore(const BlockPointerType
*T
,
420 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
421 printBefore(T
->getPointeeType(), OS
);
425 void TypePrinter::printBlockPointerAfter(const BlockPointerType
*T
,
427 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
428 printAfter(T
->getPointeeType(), OS
);
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.
433 static QualType
skipTopLevelReferences(QualType T
) {
434 if (auto *Ref
= T
->getAs
<ReferenceType
>())
435 return skipTopLevelReferences(Ref
->getPointeeTypeAsWritten());
439 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType
*T
,
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
))
452 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType
*T
,
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
))
461 printAfter(Inner
, OS
);
464 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType
*T
,
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
))
477 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType
*T
,
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
))
486 printAfter(Inner
, OS
);
489 void TypePrinter::printMemberPointerBefore(const MemberPointerType
*T
,
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()))
499 PrintingPolicy
InnerPolicy(Policy
);
500 InnerPolicy
.IncludeTagDefinition
= false;
501 TypePrinter(InnerPolicy
).print(QualType(T
->getClass(), 0), OS
, StringRef());
506 void TypePrinter::printMemberPointerAfter(const MemberPointerType
*T
,
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()))
514 printAfter(T
->getPointeeType(), OS
);
517 void TypePrinter::printConstantArrayBefore(const ConstantArrayType
*T
,
519 IncludeStrongLifetimeRAII
Strong(Policy
);
520 printBefore(T
->getElementType(), OS
);
523 void TypePrinter::printConstantArrayAfter(const ConstantArrayType
*T
,
526 if (T
->getIndexTypeQualifiers().hasQualifiers()) {
527 AppendTypeQualList(OS
, T
->getIndexTypeCVRQualifiers(),
532 if (T
->getSizeModifier() == ArrayType::Static
)
535 OS
<< T
->getSize().getZExtValue() << ']';
536 printAfter(T
->getElementType(), OS
);
539 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType
*T
,
541 IncludeStrongLifetimeRAII
Strong(Policy
);
542 printBefore(T
->getElementType(), OS
);
545 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType
*T
,
548 printAfter(T
->getElementType(), OS
);
551 void TypePrinter::printVariableArrayBefore(const VariableArrayType
*T
,
553 IncludeStrongLifetimeRAII
Strong(Policy
);
554 printBefore(T
->getElementType(), OS
);
557 void TypePrinter::printVariableArrayAfter(const VariableArrayType
*T
,
560 if (T
->getIndexTypeQualifiers().hasQualifiers()) {
561 AppendTypeQualList(OS
, T
->getIndexTypeCVRQualifiers(), Policy
.Restrict
);
565 if (T
->getSizeModifier() == VariableArrayType::Static
)
567 else if (T
->getSizeModifier() == VariableArrayType::Star
)
570 if (T
->getSizeExpr())
571 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
574 printAfter(T
->getElementType(), OS
);
577 void TypePrinter::printAdjustedBefore(const AdjustedType
*T
, raw_ostream
&OS
) {
578 // Print the adjusted representation, otherwise the adjustment will be
580 printBefore(T
->getAdjustedType(), OS
);
583 void TypePrinter::printAdjustedAfter(const AdjustedType
*T
, raw_ostream
&OS
) {
584 printAfter(T
->getAdjustedType(), OS
);
587 void TypePrinter::printDecayedBefore(const DecayedType
*T
, raw_ostream
&OS
) {
588 // Print as though it's a pointer.
589 printAdjustedBefore(T
, OS
);
592 void TypePrinter::printDecayedAfter(const DecayedType
*T
, raw_ostream
&OS
) {
593 printAdjustedAfter(T
, OS
);
596 void TypePrinter::printDependentSizedArrayBefore(
597 const DependentSizedArrayType
*T
,
599 IncludeStrongLifetimeRAII
Strong(Policy
);
600 printBefore(T
->getElementType(), OS
);
603 void TypePrinter::printDependentSizedArrayAfter(
604 const DependentSizedArrayType
*T
,
607 if (T
->getSizeExpr())
608 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
610 printAfter(T
->getElementType(), OS
);
613 void TypePrinter::printDependentAddressSpaceBefore(
614 const DependentAddressSpaceType
*T
, raw_ostream
&OS
) {
615 printBefore(T
->getPointeeType(), 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
);
624 printAfter(T
->getPointeeType(), OS
);
627 void TypePrinter::printDependentSizedExtVectorBefore(
628 const DependentSizedExtVectorType
*T
,
630 printBefore(T
->getElementType(), OS
);
633 void TypePrinter::printDependentSizedExtVectorAfter(
634 const DependentSizedExtVectorType
*T
,
636 OS
<< " __attribute__((ext_vector_type(";
637 if (T
->getSizeExpr())
638 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
640 printAfter(T
->getElementType(), OS
);
643 void TypePrinter::printVectorBefore(const VectorType
*T
, raw_ostream
&OS
) {
644 switch (T
->getVectorKind()) {
645 case VectorType::AltiVecPixel
:
646 OS
<< "__vector __pixel ";
648 case VectorType::AltiVecBool
:
649 OS
<< "__vector __bool ";
650 printBefore(T
->getElementType(), OS
);
652 case VectorType::AltiVecVector
:
654 printBefore(T
->getElementType(), OS
);
656 case VectorType::NeonVector
:
657 OS
<< "__attribute__((neon_vector_type("
658 << T
->getNumElements() << "))) ";
659 printBefore(T
->getElementType(), OS
);
661 case VectorType::NeonPolyVector
:
662 OS
<< "__attribute__((neon_polyvector_type(" <<
663 T
->getNumElements() << "))) ";
664 printBefore(T
->getElementType(), OS
);
666 case VectorType::GenericVector
: {
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()
672 print(T
->getElementType(), OS
, StringRef());
674 printBefore(T
->getElementType(), OS
);
677 case VectorType::SveFixedLengthDataVector
:
678 case VectorType::SveFixedLengthPredicateVector
:
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__(";
683 if (T
->getVectorKind() == VectorType::SveFixedLengthPredicateVector
)
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;
688 OS
<< T
->getNumElements();
691 print(T
->getElementType(), OS
, StringRef());
692 // Multiply by 8 for the number of bits.
694 printBefore(T
->getElementType(), OS
);
698 void TypePrinter::printVectorAfter(const VectorType
*T
, raw_ostream
&OS
) {
699 printAfter(T
->getElementType(), OS
);
702 void TypePrinter::printDependentVectorBefore(
703 const DependentVectorType
*T
, raw_ostream
&OS
) {
704 switch (T
->getVectorKind()) {
705 case VectorType::AltiVecPixel
:
706 OS
<< "__vector __pixel ";
708 case VectorType::AltiVecBool
:
709 OS
<< "__vector __bool ";
710 printBefore(T
->getElementType(), OS
);
712 case VectorType::AltiVecVector
:
714 printBefore(T
->getElementType(), OS
);
716 case VectorType::NeonVector
:
717 OS
<< "__attribute__((neon_vector_type(";
718 if (T
->getSizeExpr())
719 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
721 printBefore(T
->getElementType(), OS
);
723 case VectorType::NeonPolyVector
:
724 OS
<< "__attribute__((neon_polyvector_type(";
725 if (T
->getSizeExpr())
726 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
728 printBefore(T
->getElementType(), OS
);
730 case VectorType::GenericVector
: {
731 // FIXME: We prefer to print the size directly here, but have no way
732 // to get the size of the type.
733 OS
<< "__attribute__((__vector_size__(";
734 if (T
->getSizeExpr())
735 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
737 print(T
->getElementType(), OS
, StringRef());
739 printBefore(T
->getElementType(), OS
);
742 case VectorType::SveFixedLengthDataVector
:
743 case VectorType::SveFixedLengthPredicateVector
:
744 // FIXME: We prefer to print the size directly here, but have no way
745 // to get the size of the type.
746 OS
<< "__attribute__((__arm_sve_vector_bits__(";
747 if (T
->getSizeExpr()) {
748 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
749 if (T
->getVectorKind() == VectorType::SveFixedLengthPredicateVector
)
750 // Predicates take a bit per byte of the vector size, multiply by 8 to
751 // get the number of bits passed to the attribute.
754 print(T
->getElementType(), OS
, StringRef());
755 // Multiply by 8 for the number of bits.
759 printBefore(T
->getElementType(), OS
);
763 void TypePrinter::printDependentVectorAfter(
764 const DependentVectorType
*T
, raw_ostream
&OS
) {
765 printAfter(T
->getElementType(), OS
);
768 void TypePrinter::printExtVectorBefore(const ExtVectorType
*T
,
770 printBefore(T
->getElementType(), OS
);
773 void TypePrinter::printExtVectorAfter(const ExtVectorType
*T
, raw_ostream
&OS
) {
774 printAfter(T
->getElementType(), OS
);
775 OS
<< " __attribute__((ext_vector_type(";
776 OS
<< T
->getNumElements();
780 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType
*T
,
782 printBefore(T
->getElementType(), OS
);
783 OS
<< " __attribute__((matrix_type(";
784 OS
<< T
->getNumRows() << ", " << T
->getNumColumns();
788 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType
*T
,
790 printAfter(T
->getElementType(), OS
);
793 void TypePrinter::printDependentSizedMatrixBefore(
794 const DependentSizedMatrixType
*T
, raw_ostream
&OS
) {
795 printBefore(T
->getElementType(), OS
);
796 OS
<< " __attribute__((matrix_type(";
797 if (T
->getRowExpr()) {
798 T
->getRowExpr()->printPretty(OS
, nullptr, Policy
);
801 if (T
->getColumnExpr()) {
802 T
->getColumnExpr()->printPretty(OS
, nullptr, Policy
);
807 void TypePrinter::printDependentSizedMatrixAfter(
808 const DependentSizedMatrixType
*T
, raw_ostream
&OS
) {
809 printAfter(T
->getElementType(), OS
);
813 FunctionProtoType::printExceptionSpecification(raw_ostream
&OS
,
814 const PrintingPolicy
&Policy
)
816 if (hasDynamicExceptionSpec()) {
818 if (getExceptionSpecType() == EST_MSAny
)
821 for (unsigned I
= 0, N
= getNumExceptions(); I
!= N
; ++I
) {
825 OS
<< getExceptionType(I
).stream(Policy
);
828 } else if (EST_NoThrow
== getExceptionSpecType()) {
829 OS
<< " __attribute__((nothrow))";
830 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
832 // FIXME:Is it useful to print out the expression for a non-dependent
833 // noexcept specification?
834 if (isComputedNoexcept(getExceptionSpecType())) {
836 if (getNoexceptExpr())
837 getNoexceptExpr()->printPretty(OS
, nullptr, Policy
);
843 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType
*T
,
845 if (T
->hasTrailingReturn()) {
847 if (!HasEmptyPlaceHolder
)
850 // If needed for precedence reasons, wrap the inner part in grouping parens.
851 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
, false);
852 printBefore(T
->getReturnType(), OS
);
853 if (!PrevPHIsEmpty
.get())
858 StringRef
clang::getParameterABISpelling(ParameterABI ABI
) {
860 case ParameterABI::Ordinary
:
861 llvm_unreachable("asking for spelling of ordinary parameter ABI");
862 case ParameterABI::SwiftContext
:
863 return "swift_context";
864 case ParameterABI::SwiftAsyncContext
:
865 return "swift_async_context";
866 case ParameterABI::SwiftErrorResult
:
867 return "swift_error_result";
868 case ParameterABI::SwiftIndirectResult
:
869 return "swift_indirect_result";
871 llvm_unreachable("bad parameter ABI kind");
874 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType
*T
,
876 // If needed for precedence reasons, wrap the inner part in grouping parens.
877 if (!HasEmptyPlaceHolder
)
879 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
883 ParamPolicyRAII
ParamPolicy(Policy
);
884 for (unsigned i
= 0, e
= T
->getNumParams(); i
!= e
; ++i
) {
887 auto EPI
= T
->getExtParameterInfo(i
);
888 if (EPI
.isConsumed()) OS
<< "__attribute__((ns_consumed)) ";
889 if (EPI
.isNoEscape())
890 OS
<< "__attribute__((noescape)) ";
891 auto ABI
= EPI
.getABI();
892 if (ABI
!= ParameterABI::Ordinary
)
893 OS
<< "__attribute__((" << getParameterABISpelling(ABI
) << ")) ";
895 print(T
->getParamType(i
), OS
, StringRef());
899 if (T
->isVariadic()) {
900 if (T
->getNumParams())
903 } else if (T
->getNumParams() == 0 && Policy
.UseVoidForZeroParams
) {
904 // Do not emit int() if we have a proto, emit 'int(void)'.
910 FunctionType::ExtInfo Info
= T
->getExtInfo();
912 printFunctionAfter(Info
, OS
);
914 if (!T
->getMethodQuals().empty())
915 OS
<< " " << T
->getMethodQuals().getAsString();
917 switch (T
->getRefQualifier()) {
929 T
->printExceptionSpecification(OS
, Policy
);
931 if (T
->hasTrailingReturn()) {
933 print(T
->getReturnType(), OS
, StringRef());
935 printAfter(T
->getReturnType(), OS
);
938 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo
&Info
,
940 if (!InsideCCAttribute
) {
941 switch (Info
.getCC()) {
943 // The C calling convention is the default on the vast majority of platforms
944 // we support. If the user wrote it explicitly, it will usually be printed
945 // while traversing the AttributedType. If the type has been desugared, let
946 // the canonical spelling be the implicit calling convention.
947 // FIXME: It would be better to be explicit in certain contexts, such as a
948 // cdecl function typedef used to declare a member function with the
949 // Microsoft C++ ABI.
952 OS
<< " __attribute__((stdcall))";
955 OS
<< " __attribute__((fastcall))";
958 OS
<< " __attribute__((thiscall))";
960 case CC_X86VectorCall
:
961 OS
<< " __attribute__((vectorcall))";
964 OS
<< " __attribute__((pascal))";
967 OS
<< " __attribute__((pcs(\"aapcs\")))";
970 OS
<< " __attribute__((pcs(\"aapcs-vfp\")))";
972 case CC_AArch64VectorCall
:
973 OS
<< "__attribute__((aarch64_vector_pcs))";
975 case CC_AArch64SVEPCS
:
976 OS
<< "__attribute__((aarch64_sve_pcs))";
978 case CC_AMDGPUKernelCall
:
979 OS
<< "__attribute__((amdgpu_kernel))";
981 case CC_IntelOclBicc
:
982 OS
<< " __attribute__((intel_ocl_bicc))";
985 OS
<< " __attribute__((ms_abi))";
988 OS
<< " __attribute__((sysv_abi))";
991 OS
<< " __attribute__((regcall))";
993 case CC_SpirFunction
:
994 case CC_OpenCLKernel
:
995 // Do nothing. These CCs are not available as attributes.
998 OS
<< " __attribute__((swiftcall))";
1001 OS
<< "__attribute__((swiftasynccall))";
1003 case CC_PreserveMost
:
1004 OS
<< " __attribute__((preserve_most))";
1006 case CC_PreserveAll
:
1007 OS
<< " __attribute__((preserve_all))";
1012 if (Info
.getNoReturn())
1013 OS
<< " __attribute__((noreturn))";
1014 if (Info
.getCmseNSCall())
1015 OS
<< " __attribute__((cmse_nonsecure_call))";
1016 if (Info
.getProducesResult())
1017 OS
<< " __attribute__((ns_returns_retained))";
1018 if (Info
.getRegParm())
1019 OS
<< " __attribute__((regparm ("
1020 << Info
.getRegParm() << ")))";
1021 if (Info
.getNoCallerSavedRegs())
1022 OS
<< " __attribute__((no_caller_saved_registers))";
1023 if (Info
.getNoCfCheck())
1024 OS
<< " __attribute__((nocf_check))";
1027 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType
*T
,
1029 // If needed for precedence reasons, wrap the inner part in grouping parens.
1030 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
, false);
1031 printBefore(T
->getReturnType(), OS
);
1032 if (!PrevPHIsEmpty
.get())
1036 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType
*T
,
1038 // If needed for precedence reasons, wrap the inner part in grouping parens.
1039 if (!HasEmptyPlaceHolder
)
1041 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
1044 printFunctionAfter(T
->getExtInfo(), OS
);
1045 printAfter(T
->getReturnType(), OS
);
1048 void TypePrinter::printTypeSpec(NamedDecl
*D
, raw_ostream
&OS
) {
1050 // Compute the full nested-name-specifier for this type.
1051 // In C, this will always be empty except when the type
1052 // being printed is anonymous within other Record.
1053 if (!Policy
.SuppressScope
)
1054 AppendScope(D
->getDeclContext(), OS
, D
->getDeclName());
1056 IdentifierInfo
*II
= D
->getIdentifier();
1057 OS
<< II
->getName();
1058 spaceBeforePlaceHolder(OS
);
1061 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType
*T
,
1063 printTypeSpec(T
->getDecl(), OS
);
1066 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType
*T
,
1069 void TypePrinter::printUsingBefore(const UsingType
*T
, raw_ostream
&OS
) {
1070 // After `namespace b { using a::X }`, is the type X within B a::X or b::X?
1072 // - b::X is more formally correct given the UsingType model
1073 // - b::X makes sense if "re-exporting" a symbol in a new namespace
1074 // - a::X makes sense if "importing" a symbol for convenience
1076 // The "importing" use seems much more common, so we print a::X.
1077 // This could be a policy option, but the right choice seems to rest more
1078 // with the intent of the code than the caller.
1079 printTypeSpec(T
->getFoundDecl()->getUnderlyingDecl(), OS
);
1082 void TypePrinter::printUsingAfter(const UsingType
*T
, raw_ostream
&OS
) {}
1084 void TypePrinter::printTypedefBefore(const TypedefType
*T
, raw_ostream
&OS
) {
1085 printTypeSpec(T
->getDecl(), OS
);
1088 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType
*T
,
1090 StringRef MacroName
= T
->getMacroIdentifier()->getName();
1091 OS
<< MacroName
<< " ";
1093 // Since this type is meant to print the macro instead of the whole attribute,
1094 // we trim any attributes and go directly to the original modified type.
1095 printBefore(T
->getModifiedType(), OS
);
1098 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType
*T
,
1100 printAfter(T
->getModifiedType(), OS
);
1103 void TypePrinter::printTypedefAfter(const TypedefType
*T
, raw_ostream
&OS
) {}
1105 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType
*T
,
1107 OS
<< (T
->getKind() == TypeOfKind::Unqualified
? "typeof_unqual "
1109 if (T
->getUnderlyingExpr())
1110 T
->getUnderlyingExpr()->printPretty(OS
, nullptr, Policy
);
1111 spaceBeforePlaceHolder(OS
);
1114 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType
*T
,
1117 void TypePrinter::printTypeOfBefore(const TypeOfType
*T
, raw_ostream
&OS
) {
1118 OS
<< (T
->getKind() == TypeOfKind::Unqualified
? "typeof_unqual("
1120 print(T
->getUnmodifiedType(), OS
, StringRef());
1122 spaceBeforePlaceHolder(OS
);
1125 void TypePrinter::printTypeOfAfter(const TypeOfType
*T
, raw_ostream
&OS
) {}
1127 void TypePrinter::printDecltypeBefore(const DecltypeType
*T
, raw_ostream
&OS
) {
1129 if (T
->getUnderlyingExpr())
1130 T
->getUnderlyingExpr()->printPretty(OS
, nullptr, Policy
);
1132 spaceBeforePlaceHolder(OS
);
1135 void TypePrinter::printDecltypeAfter(const DecltypeType
*T
, raw_ostream
&OS
) {}
1137 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType
*T
,
1139 IncludeStrongLifetimeRAII
Strong(Policy
);
1141 static llvm::DenseMap
<int, const char *> Transformation
= {{
1142 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1143 {UnaryTransformType::Enum, "__" #Trait},
1144 #include "clang/Basic/TransformTypeTraits.def"
1146 OS
<< Transformation
[T
->getUTTKind()] << '(';
1147 print(T
->getBaseType(), OS
, StringRef());
1149 spaceBeforePlaceHolder(OS
);
1152 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType
*T
,
1155 void TypePrinter::printAutoBefore(const AutoType
*T
, raw_ostream
&OS
) {
1156 // If the type has been deduced, do not print 'auto'.
1157 if (!T
->getDeducedType().isNull()) {
1158 printBefore(T
->getDeducedType(), OS
);
1160 if (T
->isConstrained()) {
1161 // FIXME: Track a TypeConstraint as type sugar, so that we can print the
1162 // type as it was written.
1163 T
->getTypeConstraintConcept()->getDeclName().print(OS
, Policy
);
1164 auto Args
= T
->getTypeConstraintArguments();
1166 printTemplateArgumentList(
1168 T
->getTypeConstraintConcept()->getTemplateParameters());
1171 switch (T
->getKeyword()) {
1172 case AutoTypeKeyword::Auto
: OS
<< "auto"; break;
1173 case AutoTypeKeyword::DecltypeAuto
: OS
<< "decltype(auto)"; break;
1174 case AutoTypeKeyword::GNUAutoType
: OS
<< "__auto_type"; break;
1176 spaceBeforePlaceHolder(OS
);
1180 void TypePrinter::printAutoAfter(const AutoType
*T
, raw_ostream
&OS
) {
1181 // If the type has been deduced, do not print 'auto'.
1182 if (!T
->getDeducedType().isNull())
1183 printAfter(T
->getDeducedType(), OS
);
1186 void TypePrinter::printDeducedTemplateSpecializationBefore(
1187 const DeducedTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1188 // If the type has been deduced, print the deduced type.
1189 if (!T
->getDeducedType().isNull()) {
1190 printBefore(T
->getDeducedType(), OS
);
1192 IncludeStrongLifetimeRAII
Strong(Policy
);
1193 T
->getTemplateName().print(OS
, Policy
);
1194 spaceBeforePlaceHolder(OS
);
1198 void TypePrinter::printDeducedTemplateSpecializationAfter(
1199 const DeducedTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1200 // If the type has been deduced, print the deduced type.
1201 if (!T
->getDeducedType().isNull())
1202 printAfter(T
->getDeducedType(), OS
);
1205 void TypePrinter::printAtomicBefore(const AtomicType
*T
, raw_ostream
&OS
) {
1206 IncludeStrongLifetimeRAII
Strong(Policy
);
1209 print(T
->getValueType(), OS
, StringRef());
1211 spaceBeforePlaceHolder(OS
);
1214 void TypePrinter::printAtomicAfter(const AtomicType
*T
, raw_ostream
&OS
) {}
1216 void TypePrinter::printPipeBefore(const PipeType
*T
, raw_ostream
&OS
) {
1217 IncludeStrongLifetimeRAII
Strong(Policy
);
1219 if (T
->isReadOnly())
1222 OS
<< "write_only ";
1224 print(T
->getElementType(), OS
, StringRef());
1225 spaceBeforePlaceHolder(OS
);
1228 void TypePrinter::printPipeAfter(const PipeType
*T
, raw_ostream
&OS
) {}
1230 void TypePrinter::printBitIntBefore(const BitIntType
*T
, raw_ostream
&OS
) {
1231 if (T
->isUnsigned())
1233 OS
<< "_BitInt(" << T
->getNumBits() << ")";
1234 spaceBeforePlaceHolder(OS
);
1237 void TypePrinter::printBitIntAfter(const BitIntType
*T
, raw_ostream
&OS
) {}
1239 void TypePrinter::printDependentBitIntBefore(const DependentBitIntType
*T
,
1241 if (T
->isUnsigned())
1244 T
->getNumBitsExpr()->printPretty(OS
, nullptr, Policy
);
1246 spaceBeforePlaceHolder(OS
);
1249 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType
*T
,
1252 /// Appends the given scope to the end of a string.
1253 void TypePrinter::AppendScope(DeclContext
*DC
, raw_ostream
&OS
,
1254 DeclarationName NameInScope
) {
1255 if (DC
->isTranslationUnit())
1258 // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1259 // which can also print names for function and method scopes.
1260 if (DC
->isFunctionOrMethod())
1263 if (Policy
.Callbacks
&& Policy
.Callbacks
->isScopeVisible(DC
))
1266 if (const auto *NS
= dyn_cast
<NamespaceDecl
>(DC
)) {
1267 if (Policy
.SuppressUnwrittenScope
&& NS
->isAnonymousNamespace())
1268 return AppendScope(DC
->getParent(), OS
, NameInScope
);
1270 // Only suppress an inline namespace if the name has the same lookup
1271 // results in the enclosing namespace.
1272 if (Policy
.SuppressInlineNamespace
&& NS
->isInline() && NameInScope
&&
1273 NS
->isRedundantInlineQualifierFor(NameInScope
))
1274 return AppendScope(DC
->getParent(), OS
, NameInScope
);
1276 AppendScope(DC
->getParent(), OS
, NS
->getDeclName());
1277 if (NS
->getIdentifier())
1278 OS
<< NS
->getName() << "::";
1280 OS
<< "(anonymous namespace)::";
1281 } else if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(DC
)) {
1282 AppendScope(DC
->getParent(), OS
, Spec
->getDeclName());
1283 IncludeStrongLifetimeRAII
Strong(Policy
);
1284 OS
<< Spec
->getIdentifier()->getName();
1285 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
1286 printTemplateArgumentList(
1287 OS
, TemplateArgs
.asArray(), Policy
,
1288 Spec
->getSpecializedTemplate()->getTemplateParameters());
1290 } else if (const auto *Tag
= dyn_cast
<TagDecl
>(DC
)) {
1291 AppendScope(DC
->getParent(), OS
, Tag
->getDeclName());
1292 if (TypedefNameDecl
*Typedef
= Tag
->getTypedefNameForAnonDecl())
1293 OS
<< Typedef
->getIdentifier()->getName() << "::";
1294 else if (Tag
->getIdentifier())
1295 OS
<< Tag
->getIdentifier()->getName() << "::";
1299 AppendScope(DC
->getParent(), OS
, NameInScope
);
1303 void TypePrinter::printTag(TagDecl
*D
, raw_ostream
&OS
) {
1304 if (Policy
.IncludeTagDefinition
) {
1305 PrintingPolicy SubPolicy
= Policy
;
1306 SubPolicy
.IncludeTagDefinition
= false;
1307 D
->print(OS
, SubPolicy
, Indentation
);
1308 spaceBeforePlaceHolder(OS
);
1312 bool HasKindDecoration
= false;
1314 // We don't print tags unless this is an elaborated type.
1315 // In C, we just assume every RecordType is an elaborated type.
1316 if (!Policy
.SuppressTagKeyword
&& !D
->getTypedefNameForAnonDecl()) {
1317 HasKindDecoration
= true;
1318 OS
<< D
->getKindName();
1322 // Compute the full nested-name-specifier for this type.
1323 // In C, this will always be empty except when the type
1324 // being printed is anonymous within other Record.
1325 if (!Policy
.SuppressScope
)
1326 AppendScope(D
->getDeclContext(), OS
, D
->getDeclName());
1328 if (const IdentifierInfo
*II
= D
->getIdentifier())
1329 OS
<< II
->getName();
1330 else if (TypedefNameDecl
*Typedef
= D
->getTypedefNameForAnonDecl()) {
1331 assert(Typedef
->getIdentifier() && "Typedef without identifier?");
1332 OS
<< Typedef
->getIdentifier()->getName();
1334 // Make an unambiguous representation for anonymous types, e.g.
1335 // (anonymous enum at /usr/include/string.h:120:9)
1336 OS
<< (Policy
.MSVCFormatting
? '`' : '(');
1338 if (isa
<CXXRecordDecl
>(D
) && cast
<CXXRecordDecl
>(D
)->isLambda()) {
1340 HasKindDecoration
= true;
1341 } else if ((isa
<RecordDecl
>(D
) && cast
<RecordDecl
>(D
)->isAnonymousStructOrUnion())) {
1347 if (Policy
.AnonymousTagLocations
) {
1348 // Suppress the redundant tag keyword if we just printed one.
1349 // We don't have to worry about ElaboratedTypes here because you can't
1350 // refer to an anonymous type with one.
1351 if (!HasKindDecoration
)
1352 OS
<< " " << D
->getKindName();
1354 PresumedLoc PLoc
= D
->getASTContext().getSourceManager().getPresumedLoc(
1356 if (PLoc
.isValid()) {
1358 StringRef File
= PLoc
.getFilename();
1359 if (auto *Callbacks
= Policy
.Callbacks
)
1360 OS
<< Callbacks
->remapPath(File
);
1363 OS
<< ':' << PLoc
.getLine() << ':' << PLoc
.getColumn();
1367 OS
<< (Policy
.MSVCFormatting
? '\'' : ')');
1370 // If this is a class template specialization, print the template
1372 if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(D
)) {
1373 ArrayRef
<TemplateArgument
> Args
;
1374 TypeSourceInfo
*TAW
= Spec
->getTypeAsWritten();
1375 if (!Policy
.PrintCanonicalTypes
&& TAW
) {
1376 const TemplateSpecializationType
*TST
=
1377 cast
<TemplateSpecializationType
>(TAW
->getType());
1378 Args
= TST
->template_arguments();
1380 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
1381 Args
= TemplateArgs
.asArray();
1383 IncludeStrongLifetimeRAII
Strong(Policy
);
1384 printTemplateArgumentList(
1386 Spec
->getSpecializedTemplate()->getTemplateParameters());
1389 spaceBeforePlaceHolder(OS
);
1392 void TypePrinter::printRecordBefore(const RecordType
*T
, raw_ostream
&OS
) {
1393 // Print the preferred name if we have one for this type.
1394 if (Policy
.UsePreferredNames
) {
1395 for (const auto *PNA
: T
->getDecl()->specific_attrs
<PreferredNameAttr
>()) {
1396 if (!declaresSameEntity(PNA
->getTypedefType()->getAsCXXRecordDecl(),
1399 // Find the outermost typedef or alias template.
1400 QualType T
= PNA
->getTypedefType();
1402 if (auto *TT
= dyn_cast
<TypedefType
>(T
))
1403 return printTypeSpec(TT
->getDecl(), OS
);
1404 if (auto *TST
= dyn_cast
<TemplateSpecializationType
>(T
))
1405 return printTemplateId(TST
, OS
, /*FullyQualify=*/true);
1406 T
= T
->getLocallyUnqualifiedSingleStepDesugaredType();
1411 printTag(T
->getDecl(), OS
);
1414 void TypePrinter::printRecordAfter(const RecordType
*T
, raw_ostream
&OS
) {}
1416 void TypePrinter::printEnumBefore(const EnumType
*T
, raw_ostream
&OS
) {
1417 printTag(T
->getDecl(), OS
);
1420 void TypePrinter::printEnumAfter(const EnumType
*T
, raw_ostream
&OS
) {}
1422 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType
*T
,
1424 TemplateTypeParmDecl
*D
= T
->getDecl();
1425 if (D
&& D
->isImplicit()) {
1426 if (auto *TC
= D
->getTypeConstraint()) {
1427 TC
->print(OS
, Policy
);
1431 } else if (IdentifierInfo
*Id
= T
->getIdentifier())
1432 OS
<< (Policy
.CleanUglifiedParameters
? Id
->deuglifiedName()
1435 OS
<< "type-parameter-" << T
->getDepth() << '-' << T
->getIndex();
1437 spaceBeforePlaceHolder(OS
);
1440 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType
*T
,
1443 void TypePrinter::printSubstTemplateTypeParmBefore(
1444 const SubstTemplateTypeParmType
*T
,
1446 IncludeStrongLifetimeRAII
Strong(Policy
);
1447 printBefore(T
->getReplacementType(), OS
);
1450 void TypePrinter::printSubstTemplateTypeParmAfter(
1451 const SubstTemplateTypeParmType
*T
,
1453 IncludeStrongLifetimeRAII
Strong(Policy
);
1454 printAfter(T
->getReplacementType(), OS
);
1457 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1458 const SubstTemplateTypeParmPackType
*T
,
1460 IncludeStrongLifetimeRAII
Strong(Policy
);
1461 if (const TemplateTypeParmDecl
*D
= T
->getReplacedParameter()) {
1462 if (D
&& D
->isImplicit()) {
1463 if (auto *TC
= D
->getTypeConstraint()) {
1464 TC
->print(OS
, Policy
);
1468 } else if (IdentifierInfo
*Id
= D
->getIdentifier())
1469 OS
<< (Policy
.CleanUglifiedParameters
? Id
->deuglifiedName()
1472 OS
<< "type-parameter-" << D
->getDepth() << '-' << D
->getIndex();
1474 spaceBeforePlaceHolder(OS
);
1478 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1479 const SubstTemplateTypeParmPackType
*T
,
1481 IncludeStrongLifetimeRAII
Strong(Policy
);
1484 void TypePrinter::printTemplateId(const TemplateSpecializationType
*T
,
1485 raw_ostream
&OS
, bool FullyQualify
) {
1486 IncludeStrongLifetimeRAII
Strong(Policy
);
1488 TemplateDecl
*TD
= T
->getTemplateName().getAsTemplateDecl();
1489 // FIXME: Null TD never excercised in test suite.
1490 if (FullyQualify
&& TD
) {
1491 if (!Policy
.SuppressScope
)
1492 AppendScope(TD
->getDeclContext(), OS
, TD
->getDeclName());
1494 OS
<< TD
->getName();
1496 T
->getTemplateName().print(OS
, Policy
);
1499 DefaultTemplateArgsPolicyRAII
TemplateArgs(Policy
);
1500 const TemplateParameterList
*TPL
= TD
? TD
->getTemplateParameters() : nullptr;
1501 printTemplateArgumentList(OS
, T
->template_arguments(), Policy
, TPL
);
1502 spaceBeforePlaceHolder(OS
);
1505 void TypePrinter::printTemplateSpecializationBefore(
1506 const TemplateSpecializationType
*T
,
1508 printTemplateId(T
, OS
, Policy
.FullyQualifiedName
);
1511 void TypePrinter::printTemplateSpecializationAfter(
1512 const TemplateSpecializationType
*T
,
1515 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType
*T
,
1517 if (Policy
.PrintInjectedClassNameWithArguments
)
1518 return printTemplateSpecializationBefore(T
->getInjectedTST(), OS
);
1520 IncludeStrongLifetimeRAII
Strong(Policy
);
1521 T
->getTemplateName().print(OS
, Policy
);
1522 spaceBeforePlaceHolder(OS
);
1525 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType
*T
,
1528 void TypePrinter::printElaboratedBefore(const ElaboratedType
*T
,
1530 if (Policy
.IncludeTagDefinition
&& T
->getOwnedTagDecl()) {
1531 TagDecl
*OwnedTagDecl
= T
->getOwnedTagDecl();
1532 assert(OwnedTagDecl
->getTypeForDecl() == T
->getNamedType().getTypePtr() &&
1533 "OwnedTagDecl expected to be a declaration for the type");
1534 PrintingPolicy SubPolicy
= Policy
;
1535 SubPolicy
.IncludeTagDefinition
= false;
1536 OwnedTagDecl
->print(OS
, SubPolicy
, Indentation
);
1537 spaceBeforePlaceHolder(OS
);
1541 // The tag definition will take care of these.
1542 if (!Policy
.IncludeTagDefinition
)
1544 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1545 if (T
->getKeyword() != ETK_None
)
1547 NestedNameSpecifier
*Qualifier
= T
->getQualifier();
1549 Qualifier
->print(OS
, Policy
);
1552 ElaboratedTypePolicyRAII
PolicyRAII(Policy
);
1553 printBefore(T
->getNamedType(), OS
);
1556 void TypePrinter::printElaboratedAfter(const ElaboratedType
*T
,
1558 if (Policy
.IncludeTagDefinition
&& T
->getOwnedTagDecl())
1560 ElaboratedTypePolicyRAII
PolicyRAII(Policy
);
1561 printAfter(T
->getNamedType(), OS
);
1564 void TypePrinter::printParenBefore(const ParenType
*T
, raw_ostream
&OS
) {
1565 if (!HasEmptyPlaceHolder
&& !isa
<FunctionType
>(T
->getInnerType())) {
1566 printBefore(T
->getInnerType(), OS
);
1569 printBefore(T
->getInnerType(), OS
);
1572 void TypePrinter::printParenAfter(const ParenType
*T
, raw_ostream
&OS
) {
1573 if (!HasEmptyPlaceHolder
&& !isa
<FunctionType
>(T
->getInnerType())) {
1575 printAfter(T
->getInnerType(), OS
);
1577 printAfter(T
->getInnerType(), OS
);
1580 void TypePrinter::printDependentNameBefore(const DependentNameType
*T
,
1582 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1583 if (T
->getKeyword() != ETK_None
)
1586 T
->getQualifier()->print(OS
, Policy
);
1588 OS
<< T
->getIdentifier()->getName();
1589 spaceBeforePlaceHolder(OS
);
1592 void TypePrinter::printDependentNameAfter(const DependentNameType
*T
,
1595 void TypePrinter::printDependentTemplateSpecializationBefore(
1596 const DependentTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1597 IncludeStrongLifetimeRAII
Strong(Policy
);
1599 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1600 if (T
->getKeyword() != ETK_None
)
1603 if (T
->getQualifier())
1604 T
->getQualifier()->print(OS
, Policy
);
1605 OS
<< "template " << T
->getIdentifier()->getName();
1606 printTemplateArgumentList(OS
, T
->template_arguments(), Policy
);
1607 spaceBeforePlaceHolder(OS
);
1610 void TypePrinter::printDependentTemplateSpecializationAfter(
1611 const DependentTemplateSpecializationType
*T
, raw_ostream
&OS
) {}
1613 void TypePrinter::printPackExpansionBefore(const PackExpansionType
*T
,
1615 printBefore(T
->getPattern(), OS
);
1618 void TypePrinter::printPackExpansionAfter(const PackExpansionType
*T
,
1620 printAfter(T
->getPattern(), OS
);
1624 void TypePrinter::printAttributedBefore(const AttributedType
*T
,
1626 // FIXME: Generate this with TableGen.
1628 // Prefer the macro forms of the GC and ownership qualifiers.
1629 if (T
->getAttrKind() == attr::ObjCGC
||
1630 T
->getAttrKind() == attr::ObjCOwnership
)
1631 return printBefore(T
->getEquivalentType(), OS
);
1633 if (T
->getAttrKind() == attr::ObjCKindOf
)
1636 if (T
->getAttrKind() == attr::AddressSpace
)
1637 printBefore(T
->getEquivalentType(), OS
);
1639 printBefore(T
->getModifiedType(), OS
);
1641 if (T
->isMSTypeSpec()) {
1642 switch (T
->getAttrKind()) {
1644 case attr::Ptr32
: OS
<< " __ptr32"; break;
1645 case attr::Ptr64
: OS
<< " __ptr64"; break;
1646 case attr::SPtr
: OS
<< " __sptr"; break;
1647 case attr::UPtr
: OS
<< " __uptr"; break;
1649 spaceBeforePlaceHolder(OS
);
1652 // Print nullability type specifiers.
1653 if (T
->getImmediateNullability()) {
1654 if (T
->getAttrKind() == attr::TypeNonNull
)
1656 else if (T
->getAttrKind() == attr::TypeNullable
)
1658 else if (T
->getAttrKind() == attr::TypeNullUnspecified
)
1659 OS
<< " _Null_unspecified";
1660 else if (T
->getAttrKind() == attr::TypeNullableResult
)
1661 OS
<< " _Nullable_result";
1663 llvm_unreachable("unhandled nullability");
1664 spaceBeforePlaceHolder(OS
);
1668 void TypePrinter::printAttributedAfter(const AttributedType
*T
,
1670 // FIXME: Generate this with TableGen.
1672 // Prefer the macro forms of the GC and ownership qualifiers.
1673 if (T
->getAttrKind() == attr::ObjCGC
||
1674 T
->getAttrKind() == attr::ObjCOwnership
)
1675 return printAfter(T
->getEquivalentType(), OS
);
1677 // If this is a calling convention attribute, don't print the implicit CC from
1678 // the modified type.
1679 SaveAndRestore
MaybeSuppressCC(InsideCCAttribute
, T
->isCallingConv());
1681 printAfter(T
->getModifiedType(), OS
);
1683 // Some attributes are printed as qualifiers before the type, so we have
1684 // nothing left to do.
1685 if (T
->getAttrKind() == attr::ObjCKindOf
||
1686 T
->isMSTypeSpec() || T
->getImmediateNullability())
1689 // Don't print the inert __unsafe_unretained attribute at all.
1690 if (T
->getAttrKind() == attr::ObjCInertUnsafeUnretained
)
1693 // Don't print ns_returns_retained unless it had an effect.
1694 if (T
->getAttrKind() == attr::NSReturnsRetained
&&
1695 !T
->getEquivalentType()->castAs
<FunctionType
>()
1696 ->getExtInfo().getProducesResult())
1699 if (T
->getAttrKind() == attr::LifetimeBound
) {
1700 OS
<< " [[clang::lifetimebound]]";
1704 // The printing of the address_space attribute is handled by the qualifier
1705 // since it is still stored in the qualifier. Return early to prevent printing
1707 if (T
->getAttrKind() == attr::AddressSpace
)
1710 if (T
->getAttrKind() == attr::AnnotateType
) {
1711 // FIXME: Print the attribute arguments once we have a way to retrieve these
1712 // here. For the meantime, we just print `[[clang::annotate_type(...)]]`
1713 // without the arguments so that we know at least that we had _some_
1714 // annotation on the type.
1715 OS
<< " [[clang::annotate_type(...)]]";
1719 OS
<< " __attribute__((";
1720 switch (T
->getAttrKind()) {
1721 #define TYPE_ATTR(NAME)
1722 #define DECL_OR_TYPE_ATTR(NAME)
1723 #define ATTR(NAME) case attr::NAME:
1724 #include "clang/Basic/AttrList.inc"
1725 llvm_unreachable("non-type attribute attached to type");
1727 case attr::BTFTypeTag
:
1728 llvm_unreachable("BTFTypeTag attribute handled separately");
1730 case attr::OpenCLPrivateAddressSpace
:
1731 case attr::OpenCLGlobalAddressSpace
:
1732 case attr::OpenCLGlobalDeviceAddressSpace
:
1733 case attr::OpenCLGlobalHostAddressSpace
:
1734 case attr::OpenCLLocalAddressSpace
:
1735 case attr::OpenCLConstantAddressSpace
:
1736 case attr::OpenCLGenericAddressSpace
:
1737 case attr::HLSLGroupSharedAddressSpace
:
1738 // FIXME: Update printAttributedBefore to print these once we generate
1739 // AttributedType nodes for them.
1742 case attr::LifetimeBound
:
1743 case attr::TypeNonNull
:
1744 case attr::TypeNullable
:
1745 case attr::TypeNullableResult
:
1746 case attr::TypeNullUnspecified
:
1748 case attr::ObjCInertUnsafeUnretained
:
1749 case attr::ObjCKindOf
:
1750 case attr::ObjCOwnership
:
1755 case attr::AddressSpace
:
1756 case attr::CmseNSCall
:
1757 case attr::AnnotateType
:
1758 llvm_unreachable("This attribute should have been handled already");
1760 case attr::NSReturnsRetained
:
1761 OS
<< "ns_returns_retained";
1764 // FIXME: When Sema learns to form this AttributedType, avoid printing the
1765 // attribute again in printFunctionProtoAfter.
1766 case attr::AnyX86NoCfCheck
: OS
<< "nocf_check"; break;
1767 case attr::CDecl
: OS
<< "cdecl"; break;
1768 case attr::FastCall
: OS
<< "fastcall"; break;
1769 case attr::StdCall
: OS
<< "stdcall"; break;
1770 case attr::ThisCall
: OS
<< "thiscall"; break;
1771 case attr::SwiftCall
: OS
<< "swiftcall"; break;
1772 case attr::SwiftAsyncCall
: OS
<< "swiftasynccall"; break;
1773 case attr::VectorCall
: OS
<< "vectorcall"; break;
1774 case attr::Pascal
: OS
<< "pascal"; break;
1775 case attr::MSABI
: OS
<< "ms_abi"; break;
1776 case attr::SysVABI
: OS
<< "sysv_abi"; break;
1777 case attr::RegCall
: OS
<< "regcall"; break;
1780 QualType t
= T
->getEquivalentType();
1781 while (!t
->isFunctionType())
1782 t
= t
->getPointeeType();
1783 OS
<< (t
->castAs
<FunctionType
>()->getCallConv() == CC_AAPCS
?
1784 "\"aapcs\"" : "\"aapcs-vfp\"");
1788 case attr::AArch64VectorPcs
: OS
<< "aarch64_vector_pcs"; break;
1789 case attr::AArch64SVEPcs
: OS
<< "aarch64_sve_pcs"; break;
1790 case attr::AMDGPUKernelCall
: OS
<< "amdgpu_kernel"; break;
1791 case attr::IntelOclBicc
: OS
<< "inteloclbicc"; break;
1792 case attr::PreserveMost
:
1793 OS
<< "preserve_most";
1796 case attr::PreserveAll
:
1797 OS
<< "preserve_all";
1802 case attr::AcquireHandle
:
1803 OS
<< "acquire_handle";
1805 case attr::ArmMveStrictPolymorphism
:
1806 OS
<< "__clang_arm_mve_strict_polymorphism";
1812 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType
*T
,
1814 printBefore(T
->getWrappedType(), OS
);
1815 OS
<< " btf_type_tag(" << T
->getAttr()->getBTFTypeTag() << ")";
1818 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType
*T
,
1820 printAfter(T
->getWrappedType(), OS
);
1823 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType
*T
,
1825 OS
<< T
->getDecl()->getName();
1826 spaceBeforePlaceHolder(OS
);
1829 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType
*T
,
1832 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType
*T
,
1834 OS
<< T
->getDecl()->getName();
1835 if (!T
->qual_empty()) {
1836 bool isFirst
= true;
1838 for (const auto *I
: T
->quals()) {
1848 spaceBeforePlaceHolder(OS
);
1851 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType
*T
,
1854 void TypePrinter::printObjCObjectBefore(const ObjCObjectType
*T
,
1856 if (T
->qual_empty() && T
->isUnspecializedAsWritten() &&
1857 !T
->isKindOfTypeAsWritten())
1858 return printBefore(T
->getBaseType(), OS
);
1860 if (T
->isKindOfTypeAsWritten())
1863 print(T
->getBaseType(), OS
, StringRef());
1865 if (T
->isSpecializedAsWritten()) {
1866 bool isFirst
= true;
1868 for (auto typeArg
: T
->getTypeArgsAsWritten()) {
1874 print(typeArg
, OS
, StringRef());
1879 if (!T
->qual_empty()) {
1880 bool isFirst
= true;
1882 for (const auto *I
: T
->quals()) {
1892 spaceBeforePlaceHolder(OS
);
1895 void TypePrinter::printObjCObjectAfter(const ObjCObjectType
*T
,
1897 if (T
->qual_empty() && T
->isUnspecializedAsWritten() &&
1898 !T
->isKindOfTypeAsWritten())
1899 return printAfter(T
->getBaseType(), OS
);
1902 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType
*T
,
1904 printBefore(T
->getPointeeType(), OS
);
1906 // If we need to print the pointer, print it now.
1907 if (!T
->isObjCIdType() && !T
->isObjCQualifiedIdType() &&
1908 !T
->isObjCClassType() && !T
->isObjCQualifiedClassType()) {
1909 if (HasEmptyPlaceHolder
)
1915 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType
*T
,
1919 const TemplateArgument
&getArgument(const TemplateArgument
&A
) { return A
; }
1921 static const TemplateArgument
&getArgument(const TemplateArgumentLoc
&A
) {
1922 return A
.getArgument();
1925 static void printArgument(const TemplateArgument
&A
, const PrintingPolicy
&PP
,
1926 llvm::raw_ostream
&OS
, bool IncludeType
) {
1927 A
.print(PP
, OS
, IncludeType
);
1930 static void printArgument(const TemplateArgumentLoc
&A
,
1931 const PrintingPolicy
&PP
, llvm::raw_ostream
&OS
,
1933 const TemplateArgument::ArgKind
&Kind
= A
.getArgument().getKind();
1934 if (Kind
== TemplateArgument::ArgKind::Type
)
1935 return A
.getTypeSourceInfo()->getType().print(OS
, PP
);
1936 return A
.getArgument().print(PP
, OS
, IncludeType
);
1939 static bool isSubstitutedTemplateArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
1940 TemplateArgument Pattern
,
1941 ArrayRef
<TemplateArgument
> Args
,
1944 static bool isSubstitutedType(ASTContext
&Ctx
, QualType T
, QualType Pattern
,
1945 ArrayRef
<TemplateArgument
> Args
, unsigned Depth
) {
1946 if (Ctx
.hasSameType(T
, Pattern
))
1949 // A type parameter matches its argument.
1950 if (auto *TTPT
= Pattern
->getAs
<TemplateTypeParmType
>()) {
1951 if (TTPT
->getDepth() == Depth
&& TTPT
->getIndex() < Args
.size() &&
1952 Args
[TTPT
->getIndex()].getKind() == TemplateArgument::Type
) {
1953 QualType SubstArg
= Ctx
.getQualifiedType(
1954 Args
[TTPT
->getIndex()].getAsType(), Pattern
.getQualifiers());
1955 return Ctx
.hasSameType(SubstArg
, T
);
1960 // FIXME: Recurse into array types.
1962 // All other cases will need the types to be identically qualified.
1963 Qualifiers TQual
, PatQual
;
1964 T
= Ctx
.getUnqualifiedArrayType(T
, TQual
);
1965 Pattern
= Ctx
.getUnqualifiedArrayType(Pattern
, PatQual
);
1966 if (TQual
!= PatQual
)
1969 // Recurse into pointer-like types.
1971 QualType TPointee
= T
->getPointeeType();
1972 QualType PPointee
= Pattern
->getPointeeType();
1973 if (!TPointee
.isNull() && !PPointee
.isNull())
1974 return T
->getTypeClass() == Pattern
->getTypeClass() &&
1975 isSubstitutedType(Ctx
, TPointee
, PPointee
, Args
, Depth
);
1978 // Recurse into template specialization types.
1980 Pattern
.getCanonicalType()->getAs
<TemplateSpecializationType
>()) {
1981 TemplateName Template
;
1982 ArrayRef
<TemplateArgument
> TemplateArgs
;
1983 if (auto *TTST
= T
->getAs
<TemplateSpecializationType
>()) {
1984 Template
= TTST
->getTemplateName();
1985 TemplateArgs
= TTST
->template_arguments();
1986 } else if (auto *CTSD
= dyn_cast_or_null
<ClassTemplateSpecializationDecl
>(
1987 T
->getAsCXXRecordDecl())) {
1988 Template
= TemplateName(CTSD
->getSpecializedTemplate());
1989 TemplateArgs
= CTSD
->getTemplateArgs().asArray();
1994 if (!isSubstitutedTemplateArgument(Ctx
, Template
, PTST
->getTemplateName(),
1997 if (TemplateArgs
.size() != PTST
->template_arguments().size())
1999 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
2000 if (!isSubstitutedTemplateArgument(
2001 Ctx
, TemplateArgs
[I
], PTST
->template_arguments()[I
], Args
, Depth
))
2006 // FIXME: Handle more cases.
2010 /// Evaluates the expression template argument 'Pattern' and returns true
2011 /// if 'Arg' evaluates to the same result.
2012 static bool templateArgumentExpressionsEqual(ASTContext
const &Ctx
,
2013 TemplateArgument
const &Pattern
,
2014 TemplateArgument
const &Arg
) {
2015 if (Pattern
.getKind() != TemplateArgument::Expression
)
2018 // Can't evaluate value-dependent expressions so bail early
2019 Expr
const *pattern_expr
= Pattern
.getAsExpr();
2020 if (pattern_expr
->isValueDependent() ||
2021 !pattern_expr
->isIntegerConstantExpr(Ctx
))
2024 if (Arg
.getKind() == TemplateArgument::Integral
)
2025 return llvm::APSInt::isSameValue(pattern_expr
->EvaluateKnownConstInt(Ctx
),
2026 Arg
.getAsIntegral());
2028 if (Arg
.getKind() == TemplateArgument::Expression
) {
2029 Expr
const *args_expr
= Arg
.getAsExpr();
2030 if (args_expr
->isValueDependent() || !args_expr
->isIntegerConstantExpr(Ctx
))
2033 return llvm::APSInt::isSameValue(args_expr
->EvaluateKnownConstInt(Ctx
),
2034 pattern_expr
->EvaluateKnownConstInt(Ctx
));
2040 static bool isSubstitutedTemplateArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
2041 TemplateArgument Pattern
,
2042 ArrayRef
<TemplateArgument
> Args
,
2044 Arg
= Ctx
.getCanonicalTemplateArgument(Arg
);
2045 Pattern
= Ctx
.getCanonicalTemplateArgument(Pattern
);
2046 if (Arg
.structurallyEquals(Pattern
))
2049 if (Pattern
.getKind() == TemplateArgument::Expression
) {
2051 dyn_cast
<DeclRefExpr
>(Pattern
.getAsExpr()->IgnoreParenImpCasts())) {
2052 if (auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl()))
2053 return NTTP
->getDepth() == Depth
&& Args
.size() > NTTP
->getIndex() &&
2054 Args
[NTTP
->getIndex()].structurallyEquals(Arg
);
2058 if (templateArgumentExpressionsEqual(Ctx
, Pattern
, Arg
))
2061 if (Arg
.getKind() != Pattern
.getKind())
2064 if (Arg
.getKind() == TemplateArgument::Type
)
2065 return isSubstitutedType(Ctx
, Arg
.getAsType(), Pattern
.getAsType(), Args
,
2068 if (Arg
.getKind() == TemplateArgument::Template
) {
2069 TemplateDecl
*PatTD
= Pattern
.getAsTemplate().getAsTemplateDecl();
2070 if (auto *TTPD
= dyn_cast_or_null
<TemplateTemplateParmDecl
>(PatTD
))
2071 return TTPD
->getDepth() == Depth
&& Args
.size() > TTPD
->getIndex() &&
2072 Ctx
.getCanonicalTemplateArgument(Args
[TTPD
->getIndex()])
2073 .structurallyEquals(Arg
);
2076 // FIXME: Handle more cases.
2080 bool clang::isSubstitutedDefaultArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
2081 const NamedDecl
*Param
,
2082 ArrayRef
<TemplateArgument
> Args
,
2084 // An empty pack is equivalent to not providing a pack argument.
2085 if (Arg
.getKind() == TemplateArgument::Pack
&& Arg
.pack_size() == 0)
2088 if (auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
2089 return TTPD
->hasDefaultArgument() &&
2090 isSubstitutedTemplateArgument(Ctx
, Arg
, TTPD
->getDefaultArgument(),
2092 } else if (auto *TTPD
= dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
2093 return TTPD
->hasDefaultArgument() &&
2094 isSubstitutedTemplateArgument(
2095 Ctx
, Arg
, TTPD
->getDefaultArgument().getArgument(), Args
, Depth
);
2096 } else if (auto *NTTPD
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
2097 return NTTPD
->hasDefaultArgument() &&
2098 isSubstitutedTemplateArgument(Ctx
, Arg
, NTTPD
->getDefaultArgument(),
2104 template <typename TA
>
2106 printTo(raw_ostream
&OS
, ArrayRef
<TA
> Args
, const PrintingPolicy
&Policy
,
2107 const TemplateParameterList
*TPL
, bool IsPack
, unsigned ParmIndex
) {
2108 // Drop trailing template arguments that match default arguments.
2109 if (TPL
&& Policy
.SuppressDefaultTemplateArgs
&&
2110 !Policy
.PrintCanonicalTypes
&& !Args
.empty() && !IsPack
&&
2111 Args
.size() <= TPL
->size()) {
2112 llvm::SmallVector
<TemplateArgument
, 8> OrigArgs
;
2113 for (const TA
&A
: Args
)
2114 OrigArgs
.push_back(getArgument(A
));
2115 while (!Args
.empty() && getArgument(Args
.back()).getIsDefaulted())
2116 Args
= Args
.drop_back();
2119 const char *Comma
= Policy
.MSVCFormatting
? "," : ", ";
2123 bool NeedSpace
= false;
2124 bool FirstArg
= true;
2125 for (const auto &Arg
: Args
) {
2126 // Print the argument into a string.
2127 SmallString
<128> Buf
;
2128 llvm::raw_svector_ostream
ArgOS(Buf
);
2129 const TemplateArgument
&Argument
= getArgument(Arg
);
2130 if (Argument
.getKind() == TemplateArgument::Pack
) {
2131 if (Argument
.pack_size() && !FirstArg
)
2133 printTo(ArgOS
, Argument
.getPackAsArray(), Policy
, TPL
,
2134 /*IsPack*/ true, ParmIndex
);
2138 // Tries to print the argument with location info if exists.
2139 printArgument(Arg
, Policy
, ArgOS
,
2140 TemplateParameterList::shouldIncludeTypeForArgument(
2141 Policy
, TPL
, ParmIndex
));
2143 StringRef ArgString
= ArgOS
.str();
2145 // If this is the first argument and its string representation
2146 // begins with the global scope specifier ('::foo'), add a space
2147 // to avoid printing the diagraph '<:'.
2148 if (FirstArg
&& !ArgString
.empty() && ArgString
[0] == ':')
2153 // If the last character of our string is '>', add another space to
2154 // keep the two '>''s separate tokens.
2155 if (!ArgString
.empty()) {
2156 NeedSpace
= Policy
.SplitTemplateClosers
&& ArgString
.back() == '>';
2160 // Use same template parameter for all elements of Pack
2172 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2173 const TemplateArgumentListInfo
&Args
,
2174 const PrintingPolicy
&Policy
,
2175 const TemplateParameterList
*TPL
) {
2176 printTemplateArgumentList(OS
, Args
.arguments(), Policy
, TPL
);
2179 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2180 ArrayRef
<TemplateArgument
> Args
,
2181 const PrintingPolicy
&Policy
,
2182 const TemplateParameterList
*TPL
) {
2183 printTo(OS
, Args
, Policy
, TPL
, /*isPack*/ false, /*parmIndex*/ 0);
2186 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2187 ArrayRef
<TemplateArgumentLoc
> Args
,
2188 const PrintingPolicy
&Policy
,
2189 const TemplateParameterList
*TPL
) {
2190 printTo(OS
, Args
, Policy
, TPL
, /*isPack*/ false, /*parmIndex*/ 0);
2193 std::string
Qualifiers::getAsString() const {
2195 return getAsString(PrintingPolicy(LO
));
2198 // Appends qualifiers to the given string, separated by spaces. Will
2199 // prefix a space if the string is non-empty. Will not append a final
2201 std::string
Qualifiers::getAsString(const PrintingPolicy
&Policy
) const {
2202 SmallString
<64> Buf
;
2203 llvm::raw_svector_ostream
StrOS(Buf
);
2204 print(StrOS
, Policy
);
2205 return std::string(StrOS
.str());
2208 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy
&Policy
) const {
2209 if (getCVRQualifiers())
2212 if (getAddressSpace() != LangAS::Default
)
2215 if (getObjCGCAttr())
2218 if (Qualifiers::ObjCLifetime lifetime
= getObjCLifetime())
2219 if (!(lifetime
== Qualifiers::OCL_Strong
&& Policy
.SuppressStrongLifetime
))
2225 std::string
Qualifiers::getAddrSpaceAsString(LangAS AS
) {
2227 case LangAS::Default
:
2229 case LangAS::opencl_global
:
2230 case LangAS::sycl_global
:
2232 case LangAS::opencl_local
:
2233 case LangAS::sycl_local
:
2235 case LangAS::opencl_private
:
2236 case LangAS::sycl_private
:
2238 case LangAS::opencl_constant
:
2239 return "__constant";
2240 case LangAS::opencl_generic
:
2242 case LangAS::opencl_global_device
:
2243 case LangAS::sycl_global_device
:
2244 return "__global_device";
2245 case LangAS::opencl_global_host
:
2246 case LangAS::sycl_global_host
:
2247 return "__global_host";
2248 case LangAS::cuda_device
:
2249 return "__device__";
2250 case LangAS::cuda_constant
:
2251 return "__constant__";
2252 case LangAS::cuda_shared
:
2253 return "__shared__";
2254 case LangAS::ptr32_sptr
:
2255 return "__sptr __ptr32";
2256 case LangAS::ptr32_uptr
:
2257 return "__uptr __ptr32";
2260 case LangAS::hlsl_groupshared
:
2261 return "groupshared";
2263 return std::to_string(toTargetAddressSpace(AS
));
2267 // Appends qualifiers to the given string, separated by spaces. Will
2268 // prefix a space if the string is non-empty. Will not append a final
2270 void Qualifiers::print(raw_ostream
&OS
, const PrintingPolicy
& Policy
,
2271 bool appendSpaceIfNonEmpty
) const {
2272 bool addSpace
= false;
2274 unsigned quals
= getCVRQualifiers();
2276 AppendTypeQualList(OS
, quals
, Policy
.Restrict
);
2279 if (hasUnaligned()) {
2282 OS
<< "__unaligned";
2285 auto ASStr
= getAddrSpaceAsString(getAddressSpace());
2286 if (!ASStr
.empty()) {
2290 // Wrap target address space into an attribute syntax
2291 if (isTargetAddressSpace(getAddressSpace()))
2292 OS
<< "__attribute__((address_space(" << ASStr
<< ")))";
2297 if (Qualifiers::GC gc
= getObjCGCAttr()) {
2301 if (gc
== Qualifiers::Weak
)
2306 if (Qualifiers::ObjCLifetime lifetime
= getObjCLifetime()) {
2307 if (!(lifetime
== Qualifiers::OCL_Strong
&& Policy
.SuppressStrongLifetime
)){
2314 case Qualifiers::OCL_None
: llvm_unreachable("none but true");
2315 case Qualifiers::OCL_ExplicitNone
: OS
<< "__unsafe_unretained"; break;
2316 case Qualifiers::OCL_Strong
:
2317 if (!Policy
.SuppressStrongLifetime
)
2321 case Qualifiers::OCL_Weak
: OS
<< "__weak"; break;
2322 case Qualifiers::OCL_Autoreleasing
: OS
<< "__autoreleasing"; break;
2326 if (appendSpaceIfNonEmpty
&& addSpace
)
2330 std::string
QualType::getAsString() const {
2331 return getAsString(split(), LangOptions());
2334 std::string
QualType::getAsString(const PrintingPolicy
&Policy
) const {
2336 getAsStringInternal(S
, Policy
);
2340 std::string
QualType::getAsString(const Type
*ty
, Qualifiers qs
,
2341 const PrintingPolicy
&Policy
) {
2343 getAsStringInternal(ty
, qs
, buffer
, Policy
);
2347 void QualType::print(raw_ostream
&OS
, const PrintingPolicy
&Policy
,
2348 const Twine
&PlaceHolder
, unsigned Indentation
) const {
2349 print(splitAccordingToPolicy(*this, Policy
), OS
, Policy
, PlaceHolder
,
2353 void QualType::print(const Type
*ty
, Qualifiers qs
,
2354 raw_ostream
&OS
, const PrintingPolicy
&policy
,
2355 const Twine
&PlaceHolder
, unsigned Indentation
) {
2356 SmallString
<128> PHBuf
;
2357 StringRef PH
= PlaceHolder
.toStringRef(PHBuf
);
2359 TypePrinter(policy
, Indentation
).print(ty
, qs
, OS
, PH
);
2362 void QualType::getAsStringInternal(std::string
&Str
,
2363 const PrintingPolicy
&Policy
) const {
2364 return getAsStringInternal(splitAccordingToPolicy(*this, Policy
), Str
,
2368 void QualType::getAsStringInternal(const Type
*ty
, Qualifiers qs
,
2369 std::string
&buffer
,
2370 const PrintingPolicy
&policy
) {
2371 SmallString
<256> Buf
;
2372 llvm::raw_svector_ostream
StrOS(Buf
);
2373 TypePrinter(policy
).print(ty
, qs
, StrOS
, buffer
);
2374 std::string str
= std::string(StrOS
.str());
2378 raw_ostream
&clang::operator<<(raw_ostream
&OS
, QualType QT
) {
2379 SplitQualType S
= QT
.split();
2380 TypePrinter(LangOptions()).print(S
.Ty
, S
.Quals
, OS
, /*PlaceHolder=*/"");