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