Coverage Report

Created: 2022-05-17 06:19

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