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