1 //===--- DeclPrinter.cpp - Printing implementation for Decl ASTs ----------===//
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 file implements the Decl::print method, which pretty prints the
10 // AST back out to C/Objective-C/C++/Objective-C++ code.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/Basic/Module.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
26 
27 namespace {
28   class DeclPrinter : public DeclVisitor<DeclPrinter> {
29     raw_ostream &Out;
30     PrintingPolicy Policy;
31     const ASTContext &Context;
32     unsigned Indentation;
33     bool PrintInstantiation;
34 
35     raw_ostream& Indent() { return Indent(Indentation); }
36     raw_ostream& Indent(unsigned Indentation);
37     void ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls);
38 
39     void Print(AccessSpecifier AS);
40     void PrintConstructorInitializers(CXXConstructorDecl *CDecl,
41                                       std::string &Proto);
42 
43     /// Print an Objective-C method type in parentheses.
44     ///
45     /// \param Quals The Objective-C declaration qualifiers.
46     /// \param T The type to print.
47     void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,
48                              QualType T);
49 
50     void PrintObjCTypeParams(ObjCTypeParamList *Params);
51 
52   public:
53     DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
54                 const ASTContext &Context, unsigned Indentation = 0,
55                 bool PrintInstantiation = false)
56         : Out(Out), Policy(Policy), Context(Context), Indentation(Indentation),
57           PrintInstantiation(PrintInstantiation) {}
58 
59     void VisitDeclContext(DeclContext *DC, bool Indent = true);
60 
61     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
62     void VisitTypedefDecl(TypedefDecl *D);
63     void VisitTypeAliasDecl(TypeAliasDecl *D);
64     void VisitEnumDecl(EnumDecl *D);
65     void VisitRecordDecl(RecordDecl *D);
66     void VisitEnumConstantDecl(EnumConstantDecl *D);
67     void VisitEmptyDecl(EmptyDecl *D);
68     void VisitFunctionDecl(FunctionDecl *D);
69     void VisitFriendDecl(FriendDecl *D);
70     void VisitFieldDecl(FieldDecl *D);
71     void VisitVarDecl(VarDecl *D);
72     void VisitLabelDecl(LabelDecl *D);
73     void VisitParmVarDecl(ParmVarDecl *D);
74     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
75     void VisitImportDecl(ImportDecl *D);
76     void VisitStaticAssertDecl(StaticAssertDecl *D);
77     void VisitNamespaceDecl(NamespaceDecl *D);
78     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
79     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
80     void VisitCXXRecordDecl(CXXRecordDecl *D);
81     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
82     void VisitTemplateDecl(const TemplateDecl *D);
83     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
84     void VisitClassTemplateDecl(ClassTemplateDecl *D);
85     void VisitClassTemplateSpecializationDecl(
86                                             ClassTemplateSpecializationDecl *D);
87     void VisitClassTemplatePartialSpecializationDecl(
88                                      ClassTemplatePartialSpecializationDecl *D);
89     void VisitObjCMethodDecl(ObjCMethodDecl *D);
90     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
91     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
92     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
93     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
94     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
95     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
96     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
97     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
98     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
99     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
100     void VisitUsingDecl(UsingDecl *D);
101     void VisitUsingEnumDecl(UsingEnumDecl *D);
102     void VisitUsingShadowDecl(UsingShadowDecl *D);
103     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
104     void VisitOMPAllocateDecl(OMPAllocateDecl *D);
105     void VisitOMPRequiresDecl(OMPRequiresDecl *D);
106     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
107     void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
108     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
109     void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP);
110     void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *NTTP);
111 
112     void printTemplateParameters(const TemplateParameterList *Params,
113                                  bool OmitTemplateKW = false);
114     void printTemplateArguments(llvm::ArrayRef<TemplateArgument> Args,
115                                 const TemplateParameterList *Params,
116                                 bool TemplOverloaded);
117     void printTemplateArguments(llvm::ArrayRef<TemplateArgumentLoc> Args,
118                                 const TemplateParameterList *Params,
119                                 bool TemplOverloaded);
120     void prettyPrintAttributes(Decl *D);
121     void prettyPrintPragmas(Decl *D);
122     void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
123   };
124 }
125 
126 void Decl::print(raw_ostream &Out, unsigned Indentation,
127                  bool PrintInstantiation) const {
128   print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
129 }
130 
131 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
132                  unsigned Indentation, bool PrintInstantiation) const {
133   DeclPrinter Printer(Out, Policy, getASTContext(), Indentation,
134                       PrintInstantiation);
135   Printer.Visit(const_cast<Decl*>(this));
136 }
137 
138 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
139                                   bool OmitTemplateKW) const {
140   print(Out, Context, Context.getPrintingPolicy(), OmitTemplateKW);
141 }
142 
143 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
144                                   const PrintingPolicy &Policy,
145                                   bool OmitTemplateKW) const {
146   DeclPrinter Printer(Out, Policy, Context);
147   Printer.printTemplateParameters(this, OmitTemplateKW);
148 }
149 
150 static QualType GetBaseType(QualType T) {
151   // FIXME: This should be on the Type class!
152   QualType BaseType = T;
153   while (!BaseType->isSpecifierType()) {
154     if (const PointerType *PTy = BaseType->getAs<PointerType>())
155       BaseType = PTy->getPointeeType();
156     else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
157       BaseType = BPy->getPointeeType();
158     else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
159       BaseType = ATy->getElementType();
160     else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
161       BaseType = FTy->getReturnType();
162     else if (const VectorType *VTy = BaseType->getAs<VectorType>())
163       BaseType = VTy->getElementType();
164     else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
165       BaseType = RTy->getPointeeType();
166     else if (const AutoType *ATy = BaseType->getAs<AutoType>())
167       BaseType = ATy->getDeducedType();
168     else if (const ParenType *PTy = BaseType->getAs<ParenType>())
169       BaseType = PTy->desugar();
170     else
171       // This must be a syntax error.
172       break;
173   }
174   return BaseType;
175 }
176 
177 static QualType getDeclType(Decl* D) {
178   if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
179     return TDD->getUnderlyingType();
180   if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
181     return VD->getType();
182   return QualType();
183 }
184 
185 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
186                       raw_ostream &Out, const PrintingPolicy &Policy,
187                       unsigned Indentation) {
188   if (NumDecls == 1) {
189     (*Begin)->print(Out, Policy, Indentation);
190     return;
191   }
192 
193   Decl** End = Begin + NumDecls;
194   TagDecl* TD = dyn_cast<TagDecl>(*Begin);
195   if (TD)
196     ++Begin;
197 
198   PrintingPolicy SubPolicy(Policy);
199 
200   bool isFirst = true;
201   for ( ; Begin != End; ++Begin) {
202     if (isFirst) {
203       if(TD)
204         SubPolicy.IncludeTagDefinition = true;
205       SubPolicy.SuppressSpecifiers = false;
206       isFirst = false;
207     } else {
208       if (!isFirst) Out << ", ";
209       SubPolicy.IncludeTagDefinition = false;
210       SubPolicy.SuppressSpecifiers = true;
211     }
212 
213     (*Begin)->print(Out, SubPolicy, Indentation);
214   }
215 }
216 
217 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
218   // Get the translation unit
219   const DeclContext *DC = this;
220   while (!DC->isTranslationUnit())
221     DC = DC->getParent();
222 
223   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
224   DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0);
225   Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
226 }
227 
228 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
229   for (unsigned i = 0; i != Indentation; ++i)
230     Out << "  ";
231   return Out;
232 }
233 
234 void DeclPrinter::prettyPrintAttributes(Decl *D) {
235   if (Policy.PolishForDeclaration)
236     return;
237 
238   if (D->hasAttrs()) {
239     AttrVec &Attrs = D->getAttrs();
240     for (auto *A : Attrs) {
241       if (A->isInherited() || A->isImplicit())
242         continue;
243       switch (A->getKind()) {
244 #define ATTR(X)
245 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
246 #include "clang/Basic/AttrList.inc"
247         break;
248       default:
249         A->printPretty(Out, Policy);
250         break;
251       }
252     }
253   }
254 }
255 
256 void DeclPrinter::prettyPrintPragmas(Decl *D) {
257   if (Policy.PolishForDeclaration)
258     return;
259 
260   if (D->hasAttrs()) {
261     AttrVec &Attrs = D->getAttrs();
262     for (auto *A : Attrs) {
263       switch (A->getKind()) {
264 #define ATTR(X)
265 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
266 #include "clang/Basic/AttrList.inc"
267         A->printPretty(Out, Policy);
268         Indent();
269         break;
270       default:
271         break;
272       }
273     }
274   }
275 }
276 
277 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
278   // Normally, a PackExpansionType is written as T[3]... (for instance, as a
279   // template argument), but if it is the type of a declaration, the ellipsis
280   // is placed before the name being declared.
281   if (auto *PET = T->getAs<PackExpansionType>()) {
282     Pack = true;
283     T = PET->getPattern();
284   }
285   T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);
286 }
287 
288 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
289   this->Indent();
290   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
291   Out << ";\n";
292   Decls.clear();
293 
294 }
295 
296 void DeclPrinter::Print(AccessSpecifier AS) {
297   const auto AccessSpelling = getAccessSpelling(AS);
298   if (AccessSpelling.empty())
299     llvm_unreachable("No access specifier!");
300   Out << AccessSpelling;
301 }
302 
303 void DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl,
304                                                std::string &Proto) {
305   bool HasInitializerList = false;
306   for (const auto *BMInitializer : CDecl->inits()) {
307     if (BMInitializer->isInClassMemberInitializer())
308       continue;
309 
310     if (!HasInitializerList) {
311       Proto += " : ";
312       Out << Proto;
313       Proto.clear();
314       HasInitializerList = true;
315     } else
316       Out << ", ";
317 
318     if (BMInitializer->isAnyMemberInitializer()) {
319       FieldDecl *FD = BMInitializer->getAnyMember();
320       Out << *FD;
321     } else {
322       Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
323     }
324 
325     Out << "(";
326     if (!BMInitializer->getInit()) {
327       // Nothing to print
328     } else {
329       Expr *Init = BMInitializer->getInit();
330       if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
331         Init = Tmp->getSubExpr();
332 
333       Init = Init->IgnoreParens();
334 
335       Expr *SimpleInit = nullptr;
336       Expr **Args = nullptr;
337       unsigned NumArgs = 0;
338       if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
339         Args = ParenList->getExprs();
340         NumArgs = ParenList->getNumExprs();
341       } else if (CXXConstructExpr *Construct =
342                      dyn_cast<CXXConstructExpr>(Init)) {
343         Args = Construct->getArgs();
344         NumArgs = Construct->getNumArgs();
345       } else
346         SimpleInit = Init;
347 
348       if (SimpleInit)
349         SimpleInit->printPretty(Out, nullptr, Policy, Indentation, "\n",
350                                 &Context);
351       else {
352         for (unsigned I = 0; I != NumArgs; ++I) {
353           assert(Args[I] != nullptr && "Expected non-null Expr");
354           if (isa<CXXDefaultArgExpr>(Args[I]))
355             break;
356 
357           if (I)
358             Out << ", ";
359           Args[I]->printPretty(Out, nullptr, Policy, Indentation, "\n",
360                                &Context);
361         }
362       }
363     }
364     Out << ")";
365     if (BMInitializer->isPackExpansion())
366       Out << "...";
367   }
368 }
369 
370 //----------------------------------------------------------------------------
371 // Common C declarations
372 //----------------------------------------------------------------------------
373 
374 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
375   if (Policy.TerseOutput)
376     return;
377 
378   if (Indent)
379     Indentation += Policy.Indentation;
380 
381   SmallVector<Decl*, 2> Decls;
382   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
383        D != DEnd; ++D) {
384 
385     // Don't print ObjCIvarDecls, as they are printed when visiting the
386     // containing ObjCInterfaceDecl.
387     if (isa<ObjCIvarDecl>(*D))
388       continue;
389 
390     // Skip over implicit declarations in pretty-printing mode.
391     if (D->isImplicit())
392       continue;
393 
394     // Don't print implicit specializations, as they are printed when visiting
395     // corresponding templates.
396     if (auto FD = dyn_cast<FunctionDecl>(*D))
397       if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
398           !isa<ClassTemplateSpecializationDecl>(DC))
399         continue;
400 
401     // The next bits of code handle stuff like "struct {int x;} a,b"; we're
402     // forced to merge the declarations because there's no other way to
403     // refer to the struct in question.  When that struct is named instead, we
404     // also need to merge to avoid splitting off a stand-alone struct
405     // declaration that produces the warning ext_no_declarators in some
406     // contexts.
407     //
408     // This limited merging is safe without a bunch of other checks because it
409     // only merges declarations directly referring to the tag, not typedefs.
410     //
411     // Check whether the current declaration should be grouped with a previous
412     // non-free-standing tag declaration.
413     QualType CurDeclType = getDeclType(*D);
414     if (!Decls.empty() && !CurDeclType.isNull()) {
415       QualType BaseType = GetBaseType(CurDeclType);
416       if (!BaseType.isNull() && isa<ElaboratedType>(BaseType) &&
417           cast<ElaboratedType>(BaseType)->getOwnedTagDecl() == Decls[0]) {
418         Decls.push_back(*D);
419         continue;
420       }
421     }
422 
423     // If we have a merged group waiting to be handled, handle it now.
424     if (!Decls.empty())
425       ProcessDeclGroup(Decls);
426 
427     // If the current declaration is not a free standing declaration, save it
428     // so we can merge it with the subsequent declaration(s) using it.
429     if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->isFreeStanding()) {
430       Decls.push_back(*D);
431       continue;
432     }
433 
434     if (isa<AccessSpecDecl>(*D)) {
435       Indentation -= Policy.Indentation;
436       this->Indent();
437       Print(D->getAccess());
438       Out << ":\n";
439       Indentation += Policy.Indentation;
440       continue;
441     }
442 
443     this->Indent();
444     Visit(*D);
445 
446     // FIXME: Need to be able to tell the DeclPrinter when
447     const char *Terminator = nullptr;
448     if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D) ||
449         isa<OMPDeclareMapperDecl>(*D) || isa<OMPRequiresDecl>(*D) ||
450         isa<OMPAllocateDecl>(*D))
451       Terminator = nullptr;
452     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->hasBody())
453       Terminator = nullptr;
454     else if (auto FD = dyn_cast<FunctionDecl>(*D)) {
455       if (FD->isThisDeclarationADefinition())
456         Terminator = nullptr;
457       else
458         Terminator = ";";
459     } else if (auto TD = dyn_cast<FunctionTemplateDecl>(*D)) {
460       if (TD->getTemplatedDecl()->isThisDeclarationADefinition())
461         Terminator = nullptr;
462       else
463         Terminator = ";";
464     } else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
465              isa<ObjCImplementationDecl>(*D) ||
466              isa<ObjCInterfaceDecl>(*D) ||
467              isa<ObjCProtocolDecl>(*D) ||
468              isa<ObjCCategoryImplDecl>(*D) ||
469              isa<ObjCCategoryDecl>(*D))
470       Terminator = nullptr;
471     else if (isa<EnumConstantDecl>(*D)) {
472       DeclContext::decl_iterator Next = D;
473       ++Next;
474       if (Next != DEnd)
475         Terminator = ",";
476     } else
477       Terminator = ";";
478 
479     if (Terminator)
480       Out << Terminator;
481     if (!Policy.TerseOutput &&
482         ((isa<FunctionDecl>(*D) &&
483           cast<FunctionDecl>(*D)->doesThisDeclarationHaveABody()) ||
484          (isa<FunctionTemplateDecl>(*D) &&
485           cast<FunctionTemplateDecl>(*D)->getTemplatedDecl()->doesThisDeclarationHaveABody())))
486       ; // StmtPrinter already added '\n' after CompoundStmt.
487     else
488       Out << "\n";
489 
490     // Declare target attribute is special one, natural spelling for the pragma
491     // assumes "ending" construct so print it here.
492     if (D->hasAttr<OMPDeclareTargetDeclAttr>())
493       Out << "#pragma omp end declare target\n";
494   }
495 
496   if (!Decls.empty())
497     ProcessDeclGroup(Decls);
498 
499   if (Indent)
500     Indentation -= Policy.Indentation;
501 }
502 
503 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
504   VisitDeclContext(D, false);
505 }
506 
507 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
508   if (!Policy.SuppressSpecifiers) {
509     Out << "typedef ";
510 
511     if (D->isModulePrivate())
512       Out << "__module_private__ ";
513   }
514   QualType Ty = D->getTypeSourceInfo()->getType();
515   Ty.print(Out, Policy, D->getName(), Indentation);
516   prettyPrintAttributes(D);
517 }
518 
519 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
520   Out << "using " << *D;
521   prettyPrintAttributes(D);
522   Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
523 }
524 
525 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
526   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
527     Out << "__module_private__ ";
528   Out << "enum";
529   if (D->isScoped()) {
530     if (D->isScopedUsingClassTag())
531       Out << " class";
532     else
533       Out << " struct";
534   }
535 
536   prettyPrintAttributes(D);
537 
538   if (D->getDeclName())
539     Out << ' ' << D->getDeclName();
540 
541   if (D->isFixed())
542     Out << " : " << D->getIntegerType().stream(Policy);
543 
544   if (D->isCompleteDefinition()) {
545     Out << " {\n";
546     VisitDeclContext(D);
547     Indent() << "}";
548   }
549 }
550 
551 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
552   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
553     Out << "__module_private__ ";
554   Out << D->getKindName();
555 
556   prettyPrintAttributes(D);
557 
558   if (D->getIdentifier())
559     Out << ' ' << *D;
560 
561   if (D->isCompleteDefinition()) {
562     Out << " {\n";
563     VisitDeclContext(D);
564     Indent() << "}";
565   }
566 }
567 
568 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
569   Out << *D;
570   prettyPrintAttributes(D);
571   if (Expr *Init = D->getInitExpr()) {
572     Out << " = ";
573     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
574   }
575 }
576 
577 static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out,
578                                    PrintingPolicy &Policy, unsigned Indentation,
579                                    const ASTContext &Context) {
580   std::string Proto = "explicit";
581   llvm::raw_string_ostream EOut(Proto);
582   if (ES.getExpr()) {
583     EOut << "(";
584     ES.getExpr()->printPretty(EOut, nullptr, Policy, Indentation, "\n",
585                               &Context);
586     EOut << ")";
587   }
588   EOut << " ";
589   EOut.flush();
590   Out << EOut.str();
591 }
592 
593 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
594   if (!D->getDescribedFunctionTemplate() &&
595       !D->isFunctionTemplateSpecialization())
596     prettyPrintPragmas(D);
597 
598   if (D->isFunctionTemplateSpecialization())
599     Out << "template<> ";
600   else if (!D->getDescribedFunctionTemplate()) {
601     for (unsigned I = 0, NumTemplateParams = D->getNumTemplateParameterLists();
602          I < NumTemplateParams; ++I)
603       printTemplateParameters(D->getTemplateParameterList(I));
604   }
605 
606   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
607   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
608   CXXDeductionGuideDecl *GuideDecl = dyn_cast<CXXDeductionGuideDecl>(D);
609   if (!Policy.SuppressSpecifiers) {
610     switch (D->getStorageClass()) {
611     case SC_None: break;
612     case SC_Extern: Out << "extern "; break;
613     case SC_Static: Out << "static "; break;
614     case SC_PrivateExtern: Out << "__private_extern__ "; break;
615     case SC_Auto: case SC_Register:
616       llvm_unreachable("invalid for functions");
617     }
618 
619     if (D->isInlineSpecified())  Out << "inline ";
620     if (D->isVirtualAsWritten()) Out << "virtual ";
621     if (D->isModulePrivate())    Out << "__module_private__ ";
622     if (D->isConstexprSpecified() && !D->isExplicitlyDefaulted())
623       Out << "constexpr ";
624     if (D->isConsteval())        Out << "consteval ";
625     ExplicitSpecifier ExplicitSpec = ExplicitSpecifier::getFromDecl(D);
626     if (ExplicitSpec.isSpecified())
627       printExplicitSpecifier(ExplicitSpec, Out, Policy, Indentation, Context);
628   }
629 
630   PrintingPolicy SubPolicy(Policy);
631   SubPolicy.SuppressSpecifiers = false;
632   std::string Proto;
633 
634   if (Policy.FullyQualifiedName) {
635     Proto += D->getQualifiedNameAsString();
636   } else {
637     llvm::raw_string_ostream OS(Proto);
638     if (!Policy.SuppressScope) {
639       if (const NestedNameSpecifier *NS = D->getQualifier()) {
640         NS->print(OS, Policy);
641       }
642     }
643     D->getNameInfo().printName(OS, Policy);
644   }
645 
646   if (GuideDecl)
647     Proto = GuideDecl->getDeducedTemplate()->getDeclName().getAsString();
648   if (D->isFunctionTemplateSpecialization()) {
649     llvm::raw_string_ostream POut(Proto);
650     DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation);
651     const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten();
652     const TemplateParameterList *TPL = D->getTemplateSpecializationInfo()
653                                            ->getTemplate()
654                                            ->getTemplateParameters();
655     if (TArgAsWritten && !Policy.PrintCanonicalTypes)
656       TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), TPL,
657                                          /*TemplOverloaded*/ true);
658     else if (const TemplateArgumentList *TArgs =
659                  D->getTemplateSpecializationArgs())
660       TArgPrinter.printTemplateArguments(TArgs->asArray(), TPL,
661                                          /*TemplOverloaded*/ true);
662   }
663 
664   QualType Ty = D->getType();
665   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
666     Proto = '(' + Proto + ')';
667     Ty = PT->getInnerType();
668   }
669 
670   if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
671     const FunctionProtoType *FT = nullptr;
672     if (D->hasWrittenPrototype())
673       FT = dyn_cast<FunctionProtoType>(AFT);
674 
675     Proto += "(";
676     if (FT) {
677       llvm::raw_string_ostream POut(Proto);
678       DeclPrinter ParamPrinter(POut, SubPolicy, Context, Indentation);
679       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
680         if (i) POut << ", ";
681         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
682       }
683 
684       if (FT->isVariadic()) {
685         if (D->getNumParams()) POut << ", ";
686         POut << "...";
687       }
688     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
689       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
690         if (i)
691           Proto += ", ";
692         Proto += D->getParamDecl(i)->getNameAsString();
693       }
694     }
695 
696     Proto += ")";
697 
698     if (FT) {
699       if (FT->isConst())
700         Proto += " const";
701       if (FT->isVolatile())
702         Proto += " volatile";
703       if (FT->isRestrict())
704         Proto += " restrict";
705 
706       switch (FT->getRefQualifier()) {
707       case RQ_None:
708         break;
709       case RQ_LValue:
710         Proto += " &";
711         break;
712       case RQ_RValue:
713         Proto += " &&";
714         break;
715       }
716     }
717 
718     if (FT && FT->hasDynamicExceptionSpec()) {
719       Proto += " throw(";
720       if (FT->getExceptionSpecType() == EST_MSAny)
721         Proto += "...";
722       else
723         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
724           if (I)
725             Proto += ", ";
726 
727           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
728         }
729       Proto += ")";
730     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
731       Proto += " noexcept";
732       if (isComputedNoexcept(FT->getExceptionSpecType())) {
733         Proto += "(";
734         llvm::raw_string_ostream EOut(Proto);
735         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
736                                            Indentation, "\n", &Context);
737         EOut.flush();
738         Proto += EOut.str();
739         Proto += ")";
740       }
741     }
742 
743     if (CDecl) {
744       if (!Policy.TerseOutput)
745         PrintConstructorInitializers(CDecl, Proto);
746     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
747       if (FT && FT->hasTrailingReturn()) {
748         if (!GuideDecl)
749           Out << "auto ";
750         Out << Proto << " -> ";
751         Proto.clear();
752       }
753       AFT->getReturnType().print(Out, Policy, Proto);
754       Proto.clear();
755     }
756     Out << Proto;
757 
758     if (Expr *TrailingRequiresClause = D->getTrailingRequiresClause()) {
759       Out << " requires ";
760       TrailingRequiresClause->printPretty(Out, nullptr, SubPolicy, Indentation,
761                                           "\n", &Context);
762     }
763   } else {
764     Ty.print(Out, Policy, Proto);
765   }
766 
767   prettyPrintAttributes(D);
768 
769   if (D->isPure())
770     Out << " = 0";
771   else if (D->isDeletedAsWritten())
772     Out << " = delete";
773   else if (D->isExplicitlyDefaulted())
774     Out << " = default";
775   else if (D->doesThisDeclarationHaveABody()) {
776     if (!Policy.TerseOutput) {
777       if (!D->hasPrototype() && D->getNumParams()) {
778         // This is a K&R function definition, so we need to print the
779         // parameters.
780         Out << '\n';
781         DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);
782         Indentation += Policy.Indentation;
783         for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
784           Indent();
785           ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
786           Out << ";\n";
787         }
788         Indentation -= Policy.Indentation;
789       } else
790         Out << ' ';
791 
792       if (D->getBody())
793         D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation, "\n",
794                                   &Context);
795     } else {
796       if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))
797         Out << " {}";
798     }
799   }
800 }
801 
802 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
803   if (TypeSourceInfo *TSI = D->getFriendType()) {
804     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
805     for (unsigned i = 0; i < NumTPLists; ++i)
806       printTemplateParameters(D->getFriendTypeTemplateParameterList(i));
807     Out << "friend ";
808     Out << " " << TSI->getType().getAsString(Policy);
809   }
810   else if (FunctionDecl *FD =
811       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
812     Out << "friend ";
813     VisitFunctionDecl(FD);
814   }
815   else if (FunctionTemplateDecl *FTD =
816            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
817     Out << "friend ";
818     VisitFunctionTemplateDecl(FTD);
819   }
820   else if (ClassTemplateDecl *CTD =
821            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
822     Out << "friend ";
823     VisitRedeclarableTemplateDecl(CTD);
824   }
825 }
826 
827 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
828   // FIXME: add printing of pragma attributes if required.
829   if (!Policy.SuppressSpecifiers && D->isMutable())
830     Out << "mutable ";
831   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
832     Out << "__module_private__ ";
833 
834   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
835          stream(Policy, D->getName(), Indentation);
836 
837   if (D->isBitField()) {
838     Out << " : ";
839     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n",
840                                   &Context);
841   }
842 
843   Expr *Init = D->getInClassInitializer();
844   if (!Policy.SuppressInitializers && Init) {
845     if (D->getInClassInitStyle() == ICIS_ListInit)
846       Out << " ";
847     else
848       Out << " = ";
849     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
850   }
851   prettyPrintAttributes(D);
852 }
853 
854 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
855   Out << *D << ":";
856 }
857 
858 void DeclPrinter::VisitVarDecl(VarDecl *D) {
859   prettyPrintPragmas(D);
860 
861   QualType T = D->getTypeSourceInfo()
862     ? D->getTypeSourceInfo()->getType()
863     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
864 
865   if (!Policy.SuppressSpecifiers) {
866     StorageClass SC = D->getStorageClass();
867     if (SC != SC_None)
868       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
869 
870     switch (D->getTSCSpec()) {
871     case TSCS_unspecified:
872       break;
873     case TSCS___thread:
874       Out << "__thread ";
875       break;
876     case TSCS__Thread_local:
877       Out << "_Thread_local ";
878       break;
879     case TSCS_thread_local:
880       Out << "thread_local ";
881       break;
882     }
883 
884     if (D->isModulePrivate())
885       Out << "__module_private__ ";
886 
887     if (D->isConstexpr()) {
888       Out << "constexpr ";
889       T.removeLocalConst();
890     }
891   }
892 
893   printDeclType(T, D->getName());
894   Expr *Init = D->getInit();
895   if (!Policy.SuppressInitializers && Init) {
896     bool ImplicitInit = false;
897     if (CXXConstructExpr *Construct =
898             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
899       if (D->getInitStyle() == VarDecl::CallInit &&
900           !Construct->isListInitialization()) {
901         ImplicitInit = Construct->getNumArgs() == 0 ||
902           Construct->getArg(0)->isDefaultArgument();
903       }
904     }
905     if (!ImplicitInit) {
906       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
907         Out << "(";
908       else if (D->getInitStyle() == VarDecl::CInit) {
909         Out << " = ";
910       }
911       PrintingPolicy SubPolicy(Policy);
912       SubPolicy.SuppressSpecifiers = false;
913       SubPolicy.IncludeTagDefinition = false;
914       Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context);
915       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
916         Out << ")";
917     }
918   }
919   prettyPrintAttributes(D);
920 }
921 
922 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
923   VisitVarDecl(D);
924 }
925 
926 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
927   Out << "__asm (";
928   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation, "\n",
929                                  &Context);
930   Out << ")";
931 }
932 
933 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
934   Out << "@import " << D->getImportedModule()->getFullModuleName()
935       << ";\n";
936 }
937 
938 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
939   Out << "static_assert(";
940   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",
941                                   &Context);
942   if (StringLiteral *SL = D->getMessage()) {
943     Out << ", ";
944     SL->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
945   }
946   Out << ")";
947 }
948 
949 //----------------------------------------------------------------------------
950 // C++ declarations
951 //----------------------------------------------------------------------------
952 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
953   if (D->isInline())
954     Out << "inline ";
955 
956   Out << "namespace ";
957   if (D->getDeclName())
958     Out << D->getDeclName() << ' ';
959   Out << "{\n";
960 
961   VisitDeclContext(D);
962   Indent() << "}";
963 }
964 
965 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
966   Out << "using namespace ";
967   if (D->getQualifier())
968     D->getQualifier()->print(Out, Policy);
969   Out << *D->getNominatedNamespaceAsWritten();
970 }
971 
972 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
973   Out << "namespace " << *D << " = ";
974   if (D->getQualifier())
975     D->getQualifier()->print(Out, Policy);
976   Out << *D->getAliasedNamespace();
977 }
978 
979 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
980   prettyPrintAttributes(D);
981 }
982 
983 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
984   // FIXME: add printing of pragma attributes if required.
985   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
986     Out << "__module_private__ ";
987   Out << D->getKindName();
988 
989   prettyPrintAttributes(D);
990 
991   if (D->getIdentifier()) {
992     Out << ' ' << *D;
993 
994     if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
995       ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray();
996       if (!Policy.PrintCanonicalTypes)
997         if (const auto* TSI = S->getTypeAsWritten())
998           if (const auto *TST =
999                   dyn_cast<TemplateSpecializationType>(TSI->getType()))
1000             Args = TST->template_arguments();
1001       printTemplateArguments(
1002           Args, S->getSpecializedTemplate()->getTemplateParameters(),
1003           /*TemplOverloaded*/ false);
1004     }
1005   }
1006 
1007   if (D->isCompleteDefinition()) {
1008     // Print the base classes
1009     if (D->getNumBases()) {
1010       Out << " : ";
1011       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
1012              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
1013         if (Base != D->bases_begin())
1014           Out << ", ";
1015 
1016         if (Base->isVirtual())
1017           Out << "virtual ";
1018 
1019         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
1020         if (AS != AS_none) {
1021           Print(AS);
1022           Out << " ";
1023         }
1024         Out << Base->getType().getAsString(Policy);
1025 
1026         if (Base->isPackExpansion())
1027           Out << "...";
1028       }
1029     }
1030 
1031     // Print the class definition
1032     // FIXME: Doesn't print access specifiers, e.g., "public:"
1033     if (Policy.TerseOutput) {
1034       Out << " {}";
1035     } else {
1036       Out << " {\n";
1037       VisitDeclContext(D);
1038       Indent() << "}";
1039     }
1040   }
1041 }
1042 
1043 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1044   const char *l;
1045   if (D->getLanguage() == LinkageSpecDecl::lang_c)
1046     l = "C";
1047   else {
1048     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
1049            "unknown language in linkage specification");
1050     l = "C++";
1051   }
1052 
1053   Out << "extern \"" << l << "\" ";
1054   if (D->hasBraces()) {
1055     Out << "{\n";
1056     VisitDeclContext(D);
1057     Indent() << "}";
1058   } else
1059     Visit(*D->decls_begin());
1060 }
1061 
1062 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,
1063                                           bool OmitTemplateKW) {
1064   assert(Params);
1065 
1066   if (!OmitTemplateKW)
1067     Out << "template ";
1068   Out << '<';
1069 
1070   bool NeedComma = false;
1071   for (const Decl *Param : *Params) {
1072     if (Param->isImplicit())
1073       continue;
1074 
1075     if (NeedComma)
1076       Out << ", ";
1077     else
1078       NeedComma = true;
1079 
1080     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
1081       VisitTemplateTypeParmDecl(TTP);
1082     } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1083       VisitNonTypeTemplateParmDecl(NTTP);
1084     } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
1085       VisitTemplateDecl(TTPD);
1086       // FIXME: print the default argument, if present.
1087     }
1088   }
1089 
1090   Out << '>';
1091   if (!OmitTemplateKW)
1092     Out << ' ';
1093 }
1094 
1095 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args,
1096                                          const TemplateParameterList *Params,
1097                                          bool TemplOverloaded) {
1098   Out << "<";
1099   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1100     if (I)
1101       Out << ", ";
1102     if (TemplOverloaded || !Params)
1103       Args[I].print(Policy, Out, /*IncludeType*/ true);
1104     else
1105       Args[I].print(
1106           Policy, Out,
1107           TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
1108   }
1109   Out << ">";
1110 }
1111 
1112 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
1113                                          const TemplateParameterList *Params,
1114                                          bool TemplOverloaded) {
1115   Out << "<";
1116   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1117     if (I)
1118       Out << ", ";
1119     if (TemplOverloaded)
1120       Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true);
1121     else
1122       Args[I].getArgument().print(
1123           Policy, Out,
1124           TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
1125   }
1126   Out << ">";
1127 }
1128 
1129 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
1130   printTemplateParameters(D->getTemplateParameters());
1131 
1132   if (const TemplateTemplateParmDecl *TTP =
1133         dyn_cast<TemplateTemplateParmDecl>(D)) {
1134     Out << "class";
1135 
1136     if (TTP->isParameterPack())
1137       Out << " ...";
1138     else if (TTP->getDeclName())
1139       Out << ' ';
1140 
1141     if (TTP->getDeclName())
1142       Out << TTP->getDeclName();
1143   } else if (auto *TD = D->getTemplatedDecl())
1144     Visit(TD);
1145   else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {
1146     Out << "concept " << Concept->getName() << " = " ;
1147     Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation,
1148                                               "\n", &Context);
1149     Out << ";";
1150   }
1151 }
1152 
1153 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1154   prettyPrintPragmas(D->getTemplatedDecl());
1155   // Print any leading template parameter lists.
1156   if (const FunctionDecl *FD = D->getTemplatedDecl()) {
1157     for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists();
1158          I < NumTemplateParams; ++I)
1159       printTemplateParameters(FD->getTemplateParameterList(I));
1160   }
1161   VisitRedeclarableTemplateDecl(D);
1162   // Declare target attribute is special one, natural spelling for the pragma
1163   // assumes "ending" construct so print it here.
1164   if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>())
1165     Out << "#pragma omp end declare target\n";
1166 
1167   // Never print "instantiations" for deduction guides (they don't really
1168   // have them).
1169   if (PrintInstantiation &&
1170       !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) {
1171     FunctionDecl *PrevDecl = D->getTemplatedDecl();
1172     const FunctionDecl *Def;
1173     if (PrevDecl->isDefined(Def) && Def != PrevDecl)
1174       return;
1175     for (auto *I : D->specializations())
1176       if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) {
1177         if (!PrevDecl->isThisDeclarationADefinition())
1178           Out << ";\n";
1179         Indent();
1180         prettyPrintPragmas(I);
1181         Visit(I);
1182       }
1183   }
1184 }
1185 
1186 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1187   VisitRedeclarableTemplateDecl(D);
1188 
1189   if (PrintInstantiation) {
1190     for (auto *I : D->specializations())
1191       if (I->getSpecializationKind() == TSK_ImplicitInstantiation) {
1192         if (D->isThisDeclarationADefinition())
1193           Out << ";";
1194         Out << "\n";
1195         Visit(I);
1196       }
1197   }
1198 }
1199 
1200 void DeclPrinter::VisitClassTemplateSpecializationDecl(
1201                                            ClassTemplateSpecializationDecl *D) {
1202   Out << "template<> ";
1203   VisitCXXRecordDecl(D);
1204 }
1205 
1206 void DeclPrinter::VisitClassTemplatePartialSpecializationDecl(
1207                                     ClassTemplatePartialSpecializationDecl *D) {
1208   printTemplateParameters(D->getTemplateParameters());
1209   VisitCXXRecordDecl(D);
1210 }
1211 
1212 //----------------------------------------------------------------------------
1213 // Objective-C declarations
1214 //----------------------------------------------------------------------------
1215 
1216 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
1217                                       Decl::ObjCDeclQualifier Quals,
1218                                       QualType T) {
1219   Out << '(';
1220   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1221     Out << "in ";
1222   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1223     Out << "inout ";
1224   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1225     Out << "out ";
1226   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1227     Out << "bycopy ";
1228   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1229     Out << "byref ";
1230   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1231     Out << "oneway ";
1232   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1233     if (auto nullability = AttributedType::stripOuterNullability(T))
1234       Out << getNullabilitySpelling(*nullability, true) << ' ';
1235   }
1236 
1237   Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1238   Out << ')';
1239 }
1240 
1241 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1242   Out << "<";
1243   unsigned First = true;
1244   for (auto *Param : *Params) {
1245     if (First) {
1246       First = false;
1247     } else {
1248       Out << ", ";
1249     }
1250 
1251     switch (Param->getVariance()) {
1252     case ObjCTypeParamVariance::Invariant:
1253       break;
1254 
1255     case ObjCTypeParamVariance::Covariant:
1256       Out << "__covariant ";
1257       break;
1258 
1259     case ObjCTypeParamVariance::Contravariant:
1260       Out << "__contravariant ";
1261       break;
1262     }
1263 
1264     Out << Param->getDeclName();
1265 
1266     if (Param->hasExplicitBound()) {
1267       Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1268     }
1269   }
1270   Out << ">";
1271 }
1272 
1273 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1274   if (OMD->isInstanceMethod())
1275     Out << "- ";
1276   else
1277     Out << "+ ";
1278   if (!OMD->getReturnType().isNull()) {
1279     PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1280                         OMD->getReturnType());
1281   }
1282 
1283   std::string name = OMD->getSelector().getAsString();
1284   std::string::size_type pos, lastPos = 0;
1285   for (const auto *PI : OMD->parameters()) {
1286     // FIXME: selector is missing here!
1287     pos = name.find_first_of(':', lastPos);
1288     if (lastPos != 0)
1289       Out << " ";
1290     Out << name.substr(lastPos, pos - lastPos) << ':';
1291     PrintObjCMethodType(OMD->getASTContext(),
1292                         PI->getObjCDeclQualifier(),
1293                         PI->getType());
1294     Out << *PI;
1295     lastPos = pos + 1;
1296   }
1297 
1298   if (OMD->param_begin() == OMD->param_end())
1299     Out << name;
1300 
1301   if (OMD->isVariadic())
1302       Out << ", ...";
1303 
1304   prettyPrintAttributes(OMD);
1305 
1306   if (OMD->getBody() && !Policy.TerseOutput) {
1307     Out << ' ';
1308     OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n",
1309                                 &Context);
1310   }
1311   else if (Policy.PolishForDeclaration)
1312     Out << ';';
1313 }
1314 
1315 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1316   std::string I = OID->getNameAsString();
1317   ObjCInterfaceDecl *SID = OID->getSuperClass();
1318 
1319   bool eolnOut = false;
1320   if (SID)
1321     Out << "@implementation " << I << " : " << *SID;
1322   else
1323     Out << "@implementation " << I;
1324 
1325   if (OID->ivar_size() > 0) {
1326     Out << "{\n";
1327     eolnOut = true;
1328     Indentation += Policy.Indentation;
1329     for (const auto *I : OID->ivars()) {
1330       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1331                     getAsString(Policy) << ' ' << *I << ";\n";
1332     }
1333     Indentation -= Policy.Indentation;
1334     Out << "}\n";
1335   }
1336   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1337     Out << "\n";
1338     eolnOut = true;
1339   }
1340   VisitDeclContext(OID, false);
1341   if (!eolnOut)
1342     Out << "\n";
1343   Out << "@end";
1344 }
1345 
1346 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1347   std::string I = OID->getNameAsString();
1348   ObjCInterfaceDecl *SID = OID->getSuperClass();
1349 
1350   if (!OID->isThisDeclarationADefinition()) {
1351     Out << "@class " << I;
1352 
1353     if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1354       PrintObjCTypeParams(TypeParams);
1355     }
1356 
1357     Out << ";";
1358     return;
1359   }
1360   bool eolnOut = false;
1361   Out << "@interface " << I;
1362 
1363   if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1364     PrintObjCTypeParams(TypeParams);
1365   }
1366 
1367   if (SID)
1368     Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);
1369 
1370   // Protocols?
1371   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1372   if (!Protocols.empty()) {
1373     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1374          E = Protocols.end(); I != E; ++I)
1375       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1376     Out << "> ";
1377   }
1378 
1379   if (OID->ivar_size() > 0) {
1380     Out << "{\n";
1381     eolnOut = true;
1382     Indentation += Policy.Indentation;
1383     for (const auto *I : OID->ivars()) {
1384       Indent() << I->getASTContext()
1385                       .getUnqualifiedObjCPointerType(I->getType())
1386                       .getAsString(Policy) << ' ' << *I << ";\n";
1387     }
1388     Indentation -= Policy.Indentation;
1389     Out << "}\n";
1390   }
1391   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1392     Out << "\n";
1393     eolnOut = true;
1394   }
1395 
1396   VisitDeclContext(OID, false);
1397   if (!eolnOut)
1398     Out << "\n";
1399   Out << "@end";
1400   // FIXME: implement the rest...
1401 }
1402 
1403 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1404   if (!PID->isThisDeclarationADefinition()) {
1405     Out << "@protocol " << *PID << ";\n";
1406     return;
1407   }
1408   // Protocols?
1409   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1410   if (!Protocols.empty()) {
1411     Out << "@protocol " << *PID;
1412     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1413          E = Protocols.end(); I != E; ++I)
1414       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1415     Out << ">\n";
1416   } else
1417     Out << "@protocol " << *PID << '\n';
1418   VisitDeclContext(PID, false);
1419   Out << "@end";
1420 }
1421 
1422 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1423   Out << "@implementation ";
1424   if (const auto *CID = PID->getClassInterface())
1425     Out << *CID;
1426   else
1427     Out << "<<error-type>>";
1428   Out << '(' << *PID << ")\n";
1429 
1430   VisitDeclContext(PID, false);
1431   Out << "@end";
1432   // FIXME: implement the rest...
1433 }
1434 
1435 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1436   Out << "@interface ";
1437   if (const auto *CID = PID->getClassInterface())
1438     Out << *CID;
1439   else
1440     Out << "<<error-type>>";
1441   if (auto TypeParams = PID->getTypeParamList()) {
1442     PrintObjCTypeParams(TypeParams);
1443   }
1444   Out << "(" << *PID << ")\n";
1445   if (PID->ivar_size() > 0) {
1446     Out << "{\n";
1447     Indentation += Policy.Indentation;
1448     for (const auto *I : PID->ivars())
1449       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1450                     getAsString(Policy) << ' ' << *I << ";\n";
1451     Indentation -= Policy.Indentation;
1452     Out << "}\n";
1453   }
1454 
1455   VisitDeclContext(PID, false);
1456   Out << "@end";
1457 
1458   // FIXME: implement the rest...
1459 }
1460 
1461 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1462   Out << "@compatibility_alias " << *AID
1463       << ' ' << *AID->getClassInterface() << ";\n";
1464 }
1465 
1466 /// PrintObjCPropertyDecl - print a property declaration.
1467 ///
1468 /// Print attributes in the following order:
1469 /// - class
1470 /// - nonatomic | atomic
1471 /// - assign | retain | strong | copy | weak | unsafe_unretained
1472 /// - readwrite | readonly
1473 /// - getter & setter
1474 /// - nullability
1475 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1476   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1477     Out << "@required\n";
1478   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1479     Out << "@optional\n";
1480 
1481   QualType T = PDecl->getType();
1482 
1483   Out << "@property";
1484   if (PDecl->getPropertyAttributes() != ObjCPropertyAttribute::kind_noattr) {
1485     bool first = true;
1486     Out << "(";
1487     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_class) {
1488       Out << (first ? "" : ", ") << "class";
1489       first = false;
1490     }
1491 
1492     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_direct) {
1493       Out << (first ? "" : ", ") << "direct";
1494       first = false;
1495     }
1496 
1497     if (PDecl->getPropertyAttributes() &
1498         ObjCPropertyAttribute::kind_nonatomic) {
1499       Out << (first ? "" : ", ") << "nonatomic";
1500       first = false;
1501     }
1502     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic) {
1503       Out << (first ? "" : ", ") << "atomic";
1504       first = false;
1505     }
1506 
1507     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_assign) {
1508       Out << (first ? "" : ", ") << "assign";
1509       first = false;
1510     }
1511     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) {
1512       Out << (first ? "" : ", ") << "retain";
1513       first = false;
1514     }
1515 
1516     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_strong) {
1517       Out << (first ? "" : ", ") << "strong";
1518       first = false;
1519     }
1520     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) {
1521       Out << (first ? "" : ", ") << "copy";
1522       first = false;
1523     }
1524     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) {
1525       Out << (first ? "" : ", ") << "weak";
1526       first = false;
1527     }
1528     if (PDecl->getPropertyAttributes() &
1529         ObjCPropertyAttribute::kind_unsafe_unretained) {
1530       Out << (first ? "" : ", ") << "unsafe_unretained";
1531       first = false;
1532     }
1533 
1534     if (PDecl->getPropertyAttributes() &
1535         ObjCPropertyAttribute::kind_readwrite) {
1536       Out << (first ? "" : ", ") << "readwrite";
1537       first = false;
1538     }
1539     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly) {
1540       Out << (first ? "" : ", ") << "readonly";
1541       first = false;
1542     }
1543 
1544     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
1545       Out << (first ? "" : ", ") << "getter = ";
1546       PDecl->getGetterName().print(Out);
1547       first = false;
1548     }
1549     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
1550       Out << (first ? "" : ", ") << "setter = ";
1551       PDecl->getSetterName().print(Out);
1552       first = false;
1553     }
1554 
1555     if (PDecl->getPropertyAttributes() &
1556         ObjCPropertyAttribute::kind_nullability) {
1557       if (auto nullability = AttributedType::stripOuterNullability(T)) {
1558         if (*nullability == NullabilityKind::Unspecified &&
1559             (PDecl->getPropertyAttributes() &
1560              ObjCPropertyAttribute::kind_null_resettable)) {
1561           Out << (first ? "" : ", ") << "null_resettable";
1562         } else {
1563           Out << (first ? "" : ", ")
1564               << getNullabilitySpelling(*nullability, true);
1565         }
1566         first = false;
1567       }
1568     }
1569 
1570     (void) first; // Silence dead store warning due to idiomatic code.
1571     Out << ")";
1572   }
1573   std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1574       getAsString(Policy);
1575   Out << ' ' << TypeStr;
1576   if (!StringRef(TypeStr).endswith("*"))
1577     Out << ' ';
1578   Out << *PDecl;
1579   if (Policy.PolishForDeclaration)
1580     Out << ';';
1581 }
1582 
1583 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1584   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1585     Out << "@synthesize ";
1586   else
1587     Out << "@dynamic ";
1588   Out << *PID->getPropertyDecl();
1589   if (PID->getPropertyIvarDecl())
1590     Out << '=' << *PID->getPropertyIvarDecl();
1591 }
1592 
1593 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1594   if (!D->isAccessDeclaration())
1595     Out << "using ";
1596   if (D->hasTypename())
1597     Out << "typename ";
1598   D->getQualifier()->print(Out, Policy);
1599 
1600   // Use the correct record name when the using declaration is used for
1601   // inheriting constructors.
1602   for (const auto *Shadow : D->shadows()) {
1603     if (const auto *ConstructorShadow =
1604             dyn_cast<ConstructorUsingShadowDecl>(Shadow)) {
1605       assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext());
1606       Out << *ConstructorShadow->getNominatedBaseClass();
1607       return;
1608     }
1609   }
1610   Out << *D;
1611 }
1612 
1613 void DeclPrinter::VisitUsingEnumDecl(UsingEnumDecl *D) {
1614   Out << "using enum " << D->getEnumDecl();
1615 }
1616 
1617 void
1618 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1619   Out << "using typename ";
1620   D->getQualifier()->print(Out, Policy);
1621   Out << D->getDeclName();
1622 }
1623 
1624 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1625   if (!D->isAccessDeclaration())
1626     Out << "using ";
1627   D->getQualifier()->print(Out, Policy);
1628   Out << D->getDeclName();
1629 }
1630 
1631 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1632   // ignore
1633 }
1634 
1635 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1636   Out << "#pragma omp threadprivate";
1637   if (!D->varlist_empty()) {
1638     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1639                                                 E = D->varlist_end();
1640                                                 I != E; ++I) {
1641       Out << (I == D->varlist_begin() ? '(' : ',');
1642       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1643       ND->printQualifiedName(Out);
1644     }
1645     Out << ")";
1646   }
1647 }
1648 
1649 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
1650   Out << "#pragma omp allocate";
1651   if (!D->varlist_empty()) {
1652     for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),
1653                                            E = D->varlist_end();
1654          I != E; ++I) {
1655       Out << (I == D->varlist_begin() ? '(' : ',');
1656       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1657       ND->printQualifiedName(Out);
1658     }
1659     Out << ")";
1660   }
1661   if (!D->clauselist_empty()) {
1662     Out << " ";
1663     OMPClausePrinter Printer(Out, Policy);
1664     for (OMPClause *C : D->clauselists())
1665       Printer.Visit(C);
1666   }
1667 }
1668 
1669 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
1670   Out << "#pragma omp requires ";
1671   if (!D->clauselist_empty()) {
1672     OMPClausePrinter Printer(Out, Policy);
1673     for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)
1674       Printer.Visit(*I);
1675   }
1676 }
1677 
1678 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1679   if (!D->isInvalidDecl()) {
1680     Out << "#pragma omp declare reduction (";
1681     if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1682       const char *OpName =
1683           getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());
1684       assert(OpName && "not an overloaded operator");
1685       Out << OpName;
1686     } else {
1687       assert(D->getDeclName().isIdentifier());
1688       D->printName(Out);
1689     }
1690     Out << " : ";
1691     D->getType().print(Out, Policy);
1692     Out << " : ";
1693     D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1694     Out << ")";
1695     if (auto *Init = D->getInitializer()) {
1696       Out << " initializer(";
1697       switch (D->getInitializerKind()) {
1698       case OMPDeclareReductionDecl::DirectInit:
1699         Out << "omp_priv(";
1700         break;
1701       case OMPDeclareReductionDecl::CopyInit:
1702         Out << "omp_priv = ";
1703         break;
1704       case OMPDeclareReductionDecl::CallInit:
1705         break;
1706       }
1707       Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1708       if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit)
1709         Out << ")";
1710       Out << ")";
1711     }
1712   }
1713 }
1714 
1715 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
1716   if (!D->isInvalidDecl()) {
1717     Out << "#pragma omp declare mapper (";
1718     D->printName(Out);
1719     Out << " : ";
1720     D->getType().print(Out, Policy);
1721     Out << " ";
1722     Out << D->getVarName();
1723     Out << ")";
1724     if (!D->clauselist_empty()) {
1725       OMPClausePrinter Printer(Out, Policy);
1726       for (auto *C : D->clauselists()) {
1727         Out << " ";
1728         Printer.Visit(C);
1729       }
1730     }
1731   }
1732 }
1733 
1734 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1735   D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
1736 }
1737 
1738 void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) {
1739   if (const TypeConstraint *TC = TTP->getTypeConstraint())
1740     TC->print(Out, Policy);
1741   else if (TTP->wasDeclaredWithTypename())
1742     Out << "typename";
1743   else
1744     Out << "class";
1745 
1746   if (TTP->isParameterPack())
1747     Out << " ...";
1748   else if (TTP->getDeclName())
1749     Out << ' ';
1750 
1751   if (TTP->getDeclName())
1752     Out << TTP->getDeclName();
1753 
1754   if (TTP->hasDefaultArgument()) {
1755     Out << " = ";
1756     Out << TTP->getDefaultArgument().getAsString(Policy);
1757   }
1758 }
1759 
1760 void DeclPrinter::VisitNonTypeTemplateParmDecl(
1761     const NonTypeTemplateParmDecl *NTTP) {
1762   StringRef Name;
1763   if (IdentifierInfo *II = NTTP->getIdentifier())
1764     Name = II->getName();
1765   printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
1766 
1767   if (NTTP->hasDefaultArgument()) {
1768     Out << " = ";
1769     NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy, Indentation,
1770                                             "\n", &Context);
1771   }
1772 }
1773