1 //===- StmtPrinter.cpp - Printing implementation for Stmt 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 Stmt::dumpPretty/Stmt::printPretty methods, which
10 // pretty print the AST back out to C code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/OpenMPClause.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/Stmt.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/StmtObjC.h"
32 #include "clang/AST/StmtOpenMP.h"
33 #include "clang/AST/StmtVisitor.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/Basic/CharInfo.h"
37 #include "clang/Basic/ExpressionTraits.h"
38 #include "clang/Basic/IdentifierTable.h"
39 #include "clang/Basic/JsonSupport.h"
40 #include "clang/Basic/LLVM.h"
41 #include "clang/Basic/Lambda.h"
42 #include "clang/Basic/OpenMPKinds.h"
43 #include "clang/Basic/OperatorKinds.h"
44 #include "clang/Basic/SourceLocation.h"
45 #include "clang/Basic/TypeTraits.h"
46 #include "clang/Lex/Lexer.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/StringRef.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/Format.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <cassert>
57 #include <string>
58 
59 using namespace clang;
60 
61 //===----------------------------------------------------------------------===//
62 // StmtPrinter Visitor
63 //===----------------------------------------------------------------------===//
64 
65 namespace {
66 
67   class StmtPrinter : public StmtVisitor<StmtPrinter> {
68     raw_ostream &OS;
69     unsigned IndentLevel;
70     PrinterHelper* Helper;
71     PrintingPolicy Policy;
72     std::string NL;
73     const ASTContext *Context;
74 
75   public:
76     StmtPrinter(raw_ostream &os, PrinterHelper *helper,
77                 const PrintingPolicy &Policy, unsigned Indentation = 0,
78                 StringRef NL = "\n",
79                 const ASTContext *Context = nullptr)
80         : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy),
81           NL(NL), Context(Context) {}
82 
83     void PrintStmt(Stmt *S) {
84       PrintStmt(S, Policy.Indentation);
85     }
86 
87     void PrintStmt(Stmt *S, int SubIndent) {
88       IndentLevel += SubIndent;
89       if (S && isa<Expr>(S)) {
90         // If this is an expr used in a stmt context, indent and newline it.
91         Indent();
92         Visit(S);
93         OS << ";" << NL;
94       } else if (S) {
95         Visit(S);
96       } else {
97         Indent() << "<<<NULL STATEMENT>>>" << NL;
98       }
99       IndentLevel -= SubIndent;
100     }
101 
102     void PrintInitStmt(Stmt *S, unsigned PrefixWidth) {
103       // FIXME: Cope better with odd prefix widths.
104       IndentLevel += (PrefixWidth + 1) / 2;
105       if (auto *DS = dyn_cast<DeclStmt>(S))
106         PrintRawDeclStmt(DS);
107       else
108         PrintExpr(cast<Expr>(S));
109       OS << "; ";
110       IndentLevel -= (PrefixWidth + 1) / 2;
111     }
112 
113     void PrintControlledStmt(Stmt *S) {
114       if (auto *CS = dyn_cast<CompoundStmt>(S)) {
115         OS << " ";
116         PrintRawCompoundStmt(CS);
117         OS << NL;
118       } else {
119         OS << NL;
120         PrintStmt(S);
121       }
122     }
123 
124     void PrintRawCompoundStmt(CompoundStmt *S);
125     void PrintRawDecl(Decl *D);
126     void PrintRawDeclStmt(const DeclStmt *S);
127     void PrintRawIfStmt(IfStmt *If);
128     void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
129     void PrintCallArgs(CallExpr *E);
130     void PrintRawSEHExceptHandler(SEHExceptStmt *S);
131     void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
132     void PrintOMPExecutableDirective(OMPExecutableDirective *S,
133                                      bool ForceNoStmt = false);
134 
135     void PrintExpr(Expr *E) {
136       if (E)
137         Visit(E);
138       else
139         OS << "<null expr>";
140     }
141 
142     raw_ostream &Indent(int Delta = 0) {
143       for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
144         OS << "  ";
145       return OS;
146     }
147 
148     void Visit(Stmt* S) {
149       if (Helper && Helper->handledStmt(S,OS))
150           return;
151       else StmtVisitor<StmtPrinter>::Visit(S);
152     }
153 
154     void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
155       Indent() << "<<unknown stmt type>>" << NL;
156     }
157 
158     void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
159       OS << "<<unknown expr type>>";
160     }
161 
162     void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
163 
164 #define ABSTRACT_STMT(CLASS)
165 #define STMT(CLASS, PARENT) \
166     void Visit##CLASS(CLASS *Node);
167 #include "clang/AST/StmtNodes.inc"
168   };
169 
170 } // namespace
171 
172 //===----------------------------------------------------------------------===//
173 //  Stmt printing methods.
174 //===----------------------------------------------------------------------===//
175 
176 /// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
177 /// with no newline after the }.
178 void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
179   OS << "{" << NL;
180   for (auto *I : Node->body())
181     PrintStmt(I);
182 
183   Indent() << "}";
184 }
185 
186 void StmtPrinter::PrintRawDecl(Decl *D) {
187   D->print(OS, Policy, IndentLevel);
188 }
189 
190 void StmtPrinter::PrintRawDeclStmt(const DeclStmt *S) {
191   SmallVector<Decl *, 2> Decls(S->decls());
192   Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
193 }
194 
195 void StmtPrinter::VisitNullStmt(NullStmt *Node) {
196   Indent() << ";" << NL;
197 }
198 
199 void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
200   Indent();
201   PrintRawDeclStmt(Node);
202   OS << ";" << NL;
203 }
204 
205 void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
206   Indent();
207   PrintRawCompoundStmt(Node);
208   OS << "" << NL;
209 }
210 
211 void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
212   Indent(-1) << "case ";
213   PrintExpr(Node->getLHS());
214   if (Node->getRHS()) {
215     OS << " ... ";
216     PrintExpr(Node->getRHS());
217   }
218   OS << ":" << NL;
219 
220   PrintStmt(Node->getSubStmt(), 0);
221 }
222 
223 void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
224   Indent(-1) << "default:" << NL;
225   PrintStmt(Node->getSubStmt(), 0);
226 }
227 
228 void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
229   Indent(-1) << Node->getName() << ":" << NL;
230   PrintStmt(Node->getSubStmt(), 0);
231 }
232 
233 void StmtPrinter::VisitAttributedStmt(AttributedStmt *Node) {
234   for (const auto *Attr : Node->getAttrs()) {
235     Attr->printPretty(OS, Policy);
236   }
237 
238   PrintStmt(Node->getSubStmt(), 0);
239 }
240 
241 void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
242   OS << "if (";
243   if (If->getInit())
244     PrintInitStmt(If->getInit(), 4);
245   if (const DeclStmt *DS = If->getConditionVariableDeclStmt())
246     PrintRawDeclStmt(DS);
247   else
248     PrintExpr(If->getCond());
249   OS << ')';
250 
251   if (auto *CS = dyn_cast<CompoundStmt>(If->getThen())) {
252     OS << ' ';
253     PrintRawCompoundStmt(CS);
254     OS << (If->getElse() ? " " : NL);
255   } else {
256     OS << NL;
257     PrintStmt(If->getThen());
258     if (If->getElse()) Indent();
259   }
260 
261   if (Stmt *Else = If->getElse()) {
262     OS << "else";
263 
264     if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
265       OS << ' ';
266       PrintRawCompoundStmt(CS);
267       OS << NL;
268     } else if (auto *ElseIf = dyn_cast<IfStmt>(Else)) {
269       OS << ' ';
270       PrintRawIfStmt(ElseIf);
271     } else {
272       OS << NL;
273       PrintStmt(If->getElse());
274     }
275   }
276 }
277 
278 void StmtPrinter::VisitIfStmt(IfStmt *If) {
279   Indent();
280   PrintRawIfStmt(If);
281 }
282 
283 void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
284   Indent() << "switch (";
285   if (Node->getInit())
286     PrintInitStmt(Node->getInit(), 8);
287   if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
288     PrintRawDeclStmt(DS);
289   else
290     PrintExpr(Node->getCond());
291   OS << ")";
292   PrintControlledStmt(Node->getBody());
293 }
294 
295 void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
296   Indent() << "while (";
297   if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
298     PrintRawDeclStmt(DS);
299   else
300     PrintExpr(Node->getCond());
301   OS << ")" << NL;
302   PrintStmt(Node->getBody());
303 }
304 
305 void StmtPrinter::VisitDoStmt(DoStmt *Node) {
306   Indent() << "do ";
307   if (auto *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
308     PrintRawCompoundStmt(CS);
309     OS << " ";
310   } else {
311     OS << NL;
312     PrintStmt(Node->getBody());
313     Indent();
314   }
315 
316   OS << "while (";
317   PrintExpr(Node->getCond());
318   OS << ");" << NL;
319 }
320 
321 void StmtPrinter::VisitForStmt(ForStmt *Node) {
322   Indent() << "for (";
323   if (Node->getInit())
324     PrintInitStmt(Node->getInit(), 5);
325   else
326     OS << (Node->getCond() ? "; " : ";");
327   if (Node->getCond())
328     PrintExpr(Node->getCond());
329   OS << ";";
330   if (Node->getInc()) {
331     OS << " ";
332     PrintExpr(Node->getInc());
333   }
334   OS << ")";
335   PrintControlledStmt(Node->getBody());
336 }
337 
338 void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
339   Indent() << "for (";
340   if (auto *DS = dyn_cast<DeclStmt>(Node->getElement()))
341     PrintRawDeclStmt(DS);
342   else
343     PrintExpr(cast<Expr>(Node->getElement()));
344   OS << " in ";
345   PrintExpr(Node->getCollection());
346   OS << ")";
347   PrintControlledStmt(Node->getBody());
348 }
349 
350 void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
351   Indent() << "for (";
352   if (Node->getInit())
353     PrintInitStmt(Node->getInit(), 5);
354   PrintingPolicy SubPolicy(Policy);
355   SubPolicy.SuppressInitializers = true;
356   Node->getLoopVariable()->print(OS, SubPolicy, IndentLevel);
357   OS << " : ";
358   PrintExpr(Node->getRangeInit());
359   OS << ")";
360   PrintControlledStmt(Node->getBody());
361 }
362 
363 void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
364   Indent();
365   if (Node->isIfExists())
366     OS << "__if_exists (";
367   else
368     OS << "__if_not_exists (";
369 
370   if (NestedNameSpecifier *Qualifier
371         = Node->getQualifierLoc().getNestedNameSpecifier())
372     Qualifier->print(OS, Policy);
373 
374   OS << Node->getNameInfo() << ") ";
375 
376   PrintRawCompoundStmt(Node->getSubStmt());
377 }
378 
379 void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
380   Indent() << "goto " << Node->getLabel()->getName() << ";";
381   if (Policy.IncludeNewlines) OS << NL;
382 }
383 
384 void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
385   Indent() << "goto *";
386   PrintExpr(Node->getTarget());
387   OS << ";";
388   if (Policy.IncludeNewlines) OS << NL;
389 }
390 
391 void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
392   Indent() << "continue;";
393   if (Policy.IncludeNewlines) OS << NL;
394 }
395 
396 void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
397   Indent() << "break;";
398   if (Policy.IncludeNewlines) OS << NL;
399 }
400 
401 void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
402   Indent() << "return";
403   if (Node->getRetValue()) {
404     OS << " ";
405     PrintExpr(Node->getRetValue());
406   }
407   OS << ";";
408   if (Policy.IncludeNewlines) OS << NL;
409 }
410 
411 void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) {
412   Indent() << "asm ";
413 
414   if (Node->isVolatile())
415     OS << "volatile ";
416 
417   if (Node->isAsmGoto())
418     OS << "goto ";
419 
420   OS << "(";
421   VisitStringLiteral(Node->getAsmString());
422 
423   // Outputs
424   if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
425       Node->getNumClobbers() != 0 || Node->getNumLabels() != 0)
426     OS << " : ";
427 
428   for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
429     if (i != 0)
430       OS << ", ";
431 
432     if (!Node->getOutputName(i).empty()) {
433       OS << '[';
434       OS << Node->getOutputName(i);
435       OS << "] ";
436     }
437 
438     VisitStringLiteral(Node->getOutputConstraintLiteral(i));
439     OS << " (";
440     Visit(Node->getOutputExpr(i));
441     OS << ")";
442   }
443 
444   // Inputs
445   if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0 ||
446       Node->getNumLabels() != 0)
447     OS << " : ";
448 
449   for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
450     if (i != 0)
451       OS << ", ";
452 
453     if (!Node->getInputName(i).empty()) {
454       OS << '[';
455       OS << Node->getInputName(i);
456       OS << "] ";
457     }
458 
459     VisitStringLiteral(Node->getInputConstraintLiteral(i));
460     OS << " (";
461     Visit(Node->getInputExpr(i));
462     OS << ")";
463   }
464 
465   // Clobbers
466   if (Node->getNumClobbers() != 0 || Node->getNumLabels())
467     OS << " : ";
468 
469   for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
470     if (i != 0)
471       OS << ", ";
472 
473     VisitStringLiteral(Node->getClobberStringLiteral(i));
474   }
475 
476   // Labels
477   if (Node->getNumLabels() != 0)
478     OS << " : ";
479 
480   for (unsigned i = 0, e = Node->getNumLabels(); i != e; ++i) {
481     if (i != 0)
482       OS << ", ";
483     OS << Node->getLabelName(i);
484   }
485 
486   OS << ");";
487   if (Policy.IncludeNewlines) OS << NL;
488 }
489 
490 void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
491   // FIXME: Implement MS style inline asm statement printer.
492   Indent() << "__asm ";
493   if (Node->hasBraces())
494     OS << "{" << NL;
495   OS << Node->getAsmString() << NL;
496   if (Node->hasBraces())
497     Indent() << "}" << NL;
498 }
499 
500 void StmtPrinter::VisitCapturedStmt(CapturedStmt *Node) {
501   PrintStmt(Node->getCapturedDecl()->getBody());
502 }
503 
504 void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
505   Indent() << "@try";
506   if (auto *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
507     PrintRawCompoundStmt(TS);
508     OS << NL;
509   }
510 
511   for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
512     ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
513     Indent() << "@catch(";
514     if (catchStmt->getCatchParamDecl()) {
515       if (Decl *DS = catchStmt->getCatchParamDecl())
516         PrintRawDecl(DS);
517     }
518     OS << ")";
519     if (auto *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
520       PrintRawCompoundStmt(CS);
521       OS << NL;
522     }
523   }
524 
525   if (auto *FS = static_cast<ObjCAtFinallyStmt *>(Node->getFinallyStmt())) {
526     Indent() << "@finally";
527     PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
528     OS << NL;
529   }
530 }
531 
532 void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
533 }
534 
535 void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
536   Indent() << "@catch (...) { /* todo */ } " << NL;
537 }
538 
539 void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
540   Indent() << "@throw";
541   if (Node->getThrowExpr()) {
542     OS << " ";
543     PrintExpr(Node->getThrowExpr());
544   }
545   OS << ";" << NL;
546 }
547 
548 void StmtPrinter::VisitObjCAvailabilityCheckExpr(
549     ObjCAvailabilityCheckExpr *Node) {
550   OS << "@available(...)";
551 }
552 
553 void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
554   Indent() << "@synchronized (";
555   PrintExpr(Node->getSynchExpr());
556   OS << ")";
557   PrintRawCompoundStmt(Node->getSynchBody());
558   OS << NL;
559 }
560 
561 void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
562   Indent() << "@autoreleasepool";
563   PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
564   OS << NL;
565 }
566 
567 void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
568   OS << "catch (";
569   if (Decl *ExDecl = Node->getExceptionDecl())
570     PrintRawDecl(ExDecl);
571   else
572     OS << "...";
573   OS << ") ";
574   PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
575 }
576 
577 void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
578   Indent();
579   PrintRawCXXCatchStmt(Node);
580   OS << NL;
581 }
582 
583 void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
584   Indent() << "try ";
585   PrintRawCompoundStmt(Node->getTryBlock());
586   for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
587     OS << " ";
588     PrintRawCXXCatchStmt(Node->getHandler(i));
589   }
590   OS << NL;
591 }
592 
593 void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
594   Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
595   PrintRawCompoundStmt(Node->getTryBlock());
596   SEHExceptStmt *E = Node->getExceptHandler();
597   SEHFinallyStmt *F = Node->getFinallyHandler();
598   if(E)
599     PrintRawSEHExceptHandler(E);
600   else {
601     assert(F && "Must have a finally block...");
602     PrintRawSEHFinallyStmt(F);
603   }
604   OS << NL;
605 }
606 
607 void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
608   OS << "__finally ";
609   PrintRawCompoundStmt(Node->getBlock());
610   OS << NL;
611 }
612 
613 void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
614   OS << "__except (";
615   VisitExpr(Node->getFilterExpr());
616   OS << ")" << NL;
617   PrintRawCompoundStmt(Node->getBlock());
618   OS << NL;
619 }
620 
621 void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
622   Indent();
623   PrintRawSEHExceptHandler(Node);
624   OS << NL;
625 }
626 
627 void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
628   Indent();
629   PrintRawSEHFinallyStmt(Node);
630   OS << NL;
631 }
632 
633 void StmtPrinter::VisitSEHLeaveStmt(SEHLeaveStmt *Node) {
634   Indent() << "__leave;";
635   if (Policy.IncludeNewlines) OS << NL;
636 }
637 
638 //===----------------------------------------------------------------------===//
639 //  OpenMP directives printing methods
640 //===----------------------------------------------------------------------===//
641 
642 void StmtPrinter::PrintOMPExecutableDirective(OMPExecutableDirective *S,
643                                               bool ForceNoStmt) {
644   OMPClausePrinter Printer(OS, Policy);
645   ArrayRef<OMPClause *> Clauses = S->clauses();
646   for (auto *Clause : Clauses)
647     if (Clause && !Clause->isImplicit()) {
648       OS << ' ';
649       Printer.Visit(Clause);
650     }
651   OS << NL;
652   if (!ForceNoStmt && S->hasAssociatedStmt())
653     PrintStmt(S->getInnermostCapturedStmt()->getCapturedStmt());
654 }
655 
656 void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
657   Indent() << "#pragma omp parallel";
658   PrintOMPExecutableDirective(Node);
659 }
660 
661 void StmtPrinter::VisitOMPSimdDirective(OMPSimdDirective *Node) {
662   Indent() << "#pragma omp simd";
663   PrintOMPExecutableDirective(Node);
664 }
665 
666 void StmtPrinter::VisitOMPForDirective(OMPForDirective *Node) {
667   Indent() << "#pragma omp for";
668   PrintOMPExecutableDirective(Node);
669 }
670 
671 void StmtPrinter::VisitOMPForSimdDirective(OMPForSimdDirective *Node) {
672   Indent() << "#pragma omp for simd";
673   PrintOMPExecutableDirective(Node);
674 }
675 
676 void StmtPrinter::VisitOMPSectionsDirective(OMPSectionsDirective *Node) {
677   Indent() << "#pragma omp sections";
678   PrintOMPExecutableDirective(Node);
679 }
680 
681 void StmtPrinter::VisitOMPSectionDirective(OMPSectionDirective *Node) {
682   Indent() << "#pragma omp section";
683   PrintOMPExecutableDirective(Node);
684 }
685 
686 void StmtPrinter::VisitOMPSingleDirective(OMPSingleDirective *Node) {
687   Indent() << "#pragma omp single";
688   PrintOMPExecutableDirective(Node);
689 }
690 
691 void StmtPrinter::VisitOMPMasterDirective(OMPMasterDirective *Node) {
692   Indent() << "#pragma omp master";
693   PrintOMPExecutableDirective(Node);
694 }
695 
696 void StmtPrinter::VisitOMPCriticalDirective(OMPCriticalDirective *Node) {
697   Indent() << "#pragma omp critical";
698   if (Node->getDirectiveName().getName()) {
699     OS << " (";
700     Node->getDirectiveName().printName(OS, Policy);
701     OS << ")";
702   }
703   PrintOMPExecutableDirective(Node);
704 }
705 
706 void StmtPrinter::VisitOMPParallelForDirective(OMPParallelForDirective *Node) {
707   Indent() << "#pragma omp parallel for";
708   PrintOMPExecutableDirective(Node);
709 }
710 
711 void StmtPrinter::VisitOMPParallelForSimdDirective(
712     OMPParallelForSimdDirective *Node) {
713   Indent() << "#pragma omp parallel for simd";
714   PrintOMPExecutableDirective(Node);
715 }
716 
717 void StmtPrinter::VisitOMPParallelSectionsDirective(
718     OMPParallelSectionsDirective *Node) {
719   Indent() << "#pragma omp parallel sections";
720   PrintOMPExecutableDirective(Node);
721 }
722 
723 void StmtPrinter::VisitOMPTaskDirective(OMPTaskDirective *Node) {
724   Indent() << "#pragma omp task";
725   PrintOMPExecutableDirective(Node);
726 }
727 
728 void StmtPrinter::VisitOMPTaskyieldDirective(OMPTaskyieldDirective *Node) {
729   Indent() << "#pragma omp taskyield";
730   PrintOMPExecutableDirective(Node);
731 }
732 
733 void StmtPrinter::VisitOMPBarrierDirective(OMPBarrierDirective *Node) {
734   Indent() << "#pragma omp barrier";
735   PrintOMPExecutableDirective(Node);
736 }
737 
738 void StmtPrinter::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *Node) {
739   Indent() << "#pragma omp taskwait";
740   PrintOMPExecutableDirective(Node);
741 }
742 
743 void StmtPrinter::VisitOMPTaskgroupDirective(OMPTaskgroupDirective *Node) {
744   Indent() << "#pragma omp taskgroup";
745   PrintOMPExecutableDirective(Node);
746 }
747 
748 void StmtPrinter::VisitOMPFlushDirective(OMPFlushDirective *Node) {
749   Indent() << "#pragma omp flush";
750   PrintOMPExecutableDirective(Node);
751 }
752 
753 void StmtPrinter::VisitOMPOrderedDirective(OMPOrderedDirective *Node) {
754   Indent() << "#pragma omp ordered";
755   PrintOMPExecutableDirective(Node, Node->hasClausesOfKind<OMPDependClause>());
756 }
757 
758 void StmtPrinter::VisitOMPAtomicDirective(OMPAtomicDirective *Node) {
759   Indent() << "#pragma omp atomic";
760   PrintOMPExecutableDirective(Node);
761 }
762 
763 void StmtPrinter::VisitOMPTargetDirective(OMPTargetDirective *Node) {
764   Indent() << "#pragma omp target";
765   PrintOMPExecutableDirective(Node);
766 }
767 
768 void StmtPrinter::VisitOMPTargetDataDirective(OMPTargetDataDirective *Node) {
769   Indent() << "#pragma omp target data";
770   PrintOMPExecutableDirective(Node);
771 }
772 
773 void StmtPrinter::VisitOMPTargetEnterDataDirective(
774     OMPTargetEnterDataDirective *Node) {
775   Indent() << "#pragma omp target enter data";
776   PrintOMPExecutableDirective(Node, /*ForceNoStmt=*/true);
777 }
778 
779 void StmtPrinter::VisitOMPTargetExitDataDirective(
780     OMPTargetExitDataDirective *Node) {
781   Indent() << "#pragma omp target exit data";
782   PrintOMPExecutableDirective(Node, /*ForceNoStmt=*/true);
783 }
784 
785 void StmtPrinter::VisitOMPTargetParallelDirective(
786     OMPTargetParallelDirective *Node) {
787   Indent() << "#pragma omp target parallel";
788   PrintOMPExecutableDirective(Node);
789 }
790 
791 void StmtPrinter::VisitOMPTargetParallelForDirective(
792     OMPTargetParallelForDirective *Node) {
793   Indent() << "#pragma omp target parallel for";
794   PrintOMPExecutableDirective(Node);
795 }
796 
797 void StmtPrinter::VisitOMPTeamsDirective(OMPTeamsDirective *Node) {
798   Indent() << "#pragma omp teams";
799   PrintOMPExecutableDirective(Node);
800 }
801 
802 void StmtPrinter::VisitOMPCancellationPointDirective(
803     OMPCancellationPointDirective *Node) {
804   Indent() << "#pragma omp cancellation point "
805            << getOpenMPDirectiveName(Node->getCancelRegion());
806   PrintOMPExecutableDirective(Node);
807 }
808 
809 void StmtPrinter::VisitOMPCancelDirective(OMPCancelDirective *Node) {
810   Indent() << "#pragma omp cancel "
811            << getOpenMPDirectiveName(Node->getCancelRegion());
812   PrintOMPExecutableDirective(Node);
813 }
814 
815 void StmtPrinter::VisitOMPTaskLoopDirective(OMPTaskLoopDirective *Node) {
816   Indent() << "#pragma omp taskloop";
817   PrintOMPExecutableDirective(Node);
818 }
819 
820 void StmtPrinter::VisitOMPTaskLoopSimdDirective(
821     OMPTaskLoopSimdDirective *Node) {
822   Indent() << "#pragma omp taskloop simd";
823   PrintOMPExecutableDirective(Node);
824 }
825 
826 void StmtPrinter::VisitOMPMasterTaskLoopDirective(
827     OMPMasterTaskLoopDirective *Node) {
828   Indent() << "#pragma omp master taskloop";
829   PrintOMPExecutableDirective(Node);
830 }
831 
832 void StmtPrinter::VisitOMPMasterTaskLoopSimdDirective(
833     OMPMasterTaskLoopSimdDirective *Node) {
834   Indent() << "#pragma omp master taskloop simd";
835   PrintOMPExecutableDirective(Node);
836 }
837 
838 void StmtPrinter::VisitOMPParallelMasterTaskLoopDirective(
839     OMPParallelMasterTaskLoopDirective *Node) {
840   Indent() << "#pragma omp parallel master taskloop";
841   PrintOMPExecutableDirective(Node);
842 }
843 
844 void StmtPrinter::VisitOMPParallelMasterTaskLoopSimdDirective(
845     OMPParallelMasterTaskLoopSimdDirective *Node) {
846   Indent() << "#pragma omp parallel master taskloop simd";
847   PrintOMPExecutableDirective(Node);
848 }
849 
850 void StmtPrinter::VisitOMPDistributeDirective(OMPDistributeDirective *Node) {
851   Indent() << "#pragma omp distribute";
852   PrintOMPExecutableDirective(Node);
853 }
854 
855 void StmtPrinter::VisitOMPTargetUpdateDirective(
856     OMPTargetUpdateDirective *Node) {
857   Indent() << "#pragma omp target update";
858   PrintOMPExecutableDirective(Node, /*ForceNoStmt=*/true);
859 }
860 
861 void StmtPrinter::VisitOMPDistributeParallelForDirective(
862     OMPDistributeParallelForDirective *Node) {
863   Indent() << "#pragma omp distribute parallel for";
864   PrintOMPExecutableDirective(Node);
865 }
866 
867 void StmtPrinter::VisitOMPDistributeParallelForSimdDirective(
868     OMPDistributeParallelForSimdDirective *Node) {
869   Indent() << "#pragma omp distribute parallel for simd";
870   PrintOMPExecutableDirective(Node);
871 }
872 
873 void StmtPrinter::VisitOMPDistributeSimdDirective(
874     OMPDistributeSimdDirective *Node) {
875   Indent() << "#pragma omp distribute simd";
876   PrintOMPExecutableDirective(Node);
877 }
878 
879 void StmtPrinter::VisitOMPTargetParallelForSimdDirective(
880     OMPTargetParallelForSimdDirective *Node) {
881   Indent() << "#pragma omp target parallel for simd";
882   PrintOMPExecutableDirective(Node);
883 }
884 
885 void StmtPrinter::VisitOMPTargetSimdDirective(OMPTargetSimdDirective *Node) {
886   Indent() << "#pragma omp target simd";
887   PrintOMPExecutableDirective(Node);
888 }
889 
890 void StmtPrinter::VisitOMPTeamsDistributeDirective(
891     OMPTeamsDistributeDirective *Node) {
892   Indent() << "#pragma omp teams distribute";
893   PrintOMPExecutableDirective(Node);
894 }
895 
896 void StmtPrinter::VisitOMPTeamsDistributeSimdDirective(
897     OMPTeamsDistributeSimdDirective *Node) {
898   Indent() << "#pragma omp teams distribute simd";
899   PrintOMPExecutableDirective(Node);
900 }
901 
902 void StmtPrinter::VisitOMPTeamsDistributeParallelForSimdDirective(
903     OMPTeamsDistributeParallelForSimdDirective *Node) {
904   Indent() << "#pragma omp teams distribute parallel for simd";
905   PrintOMPExecutableDirective(Node);
906 }
907 
908 void StmtPrinter::VisitOMPTeamsDistributeParallelForDirective(
909     OMPTeamsDistributeParallelForDirective *Node) {
910   Indent() << "#pragma omp teams distribute parallel for";
911   PrintOMPExecutableDirective(Node);
912 }
913 
914 void StmtPrinter::VisitOMPTargetTeamsDirective(OMPTargetTeamsDirective *Node) {
915   Indent() << "#pragma omp target teams";
916   PrintOMPExecutableDirective(Node);
917 }
918 
919 void StmtPrinter::VisitOMPTargetTeamsDistributeDirective(
920     OMPTargetTeamsDistributeDirective *Node) {
921   Indent() << "#pragma omp target teams distribute";
922   PrintOMPExecutableDirective(Node);
923 }
924 
925 void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForDirective(
926     OMPTargetTeamsDistributeParallelForDirective *Node) {
927   Indent() << "#pragma omp target teams distribute parallel for";
928   PrintOMPExecutableDirective(Node);
929 }
930 
931 void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
932     OMPTargetTeamsDistributeParallelForSimdDirective *Node) {
933   Indent() << "#pragma omp target teams distribute parallel for simd";
934   PrintOMPExecutableDirective(Node);
935 }
936 
937 void StmtPrinter::VisitOMPTargetTeamsDistributeSimdDirective(
938     OMPTargetTeamsDistributeSimdDirective *Node) {
939   Indent() << "#pragma omp target teams distribute simd";
940   PrintOMPExecutableDirective(Node);
941 }
942 
943 //===----------------------------------------------------------------------===//
944 //  Expr printing methods.
945 //===----------------------------------------------------------------------===//
946 
947 void StmtPrinter::VisitSourceLocExpr(SourceLocExpr *Node) {
948   OS << Node->getBuiltinStr() << "()";
949 }
950 
951 void StmtPrinter::VisitConstantExpr(ConstantExpr *Node) {
952   PrintExpr(Node->getSubExpr());
953 }
954 
955 void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
956   if (const auto *OCED = dyn_cast<OMPCapturedExprDecl>(Node->getDecl())) {
957     OCED->getInit()->IgnoreImpCasts()->printPretty(OS, nullptr, Policy);
958     return;
959   }
960   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
961     Qualifier->print(OS, Policy);
962   if (Node->hasTemplateKeyword())
963     OS << "template ";
964   OS << Node->getNameInfo();
965   if (Node->hasExplicitTemplateArgs())
966     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
967 }
968 
969 void StmtPrinter::VisitDependentScopeDeclRefExpr(
970                                            DependentScopeDeclRefExpr *Node) {
971   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
972     Qualifier->print(OS, Policy);
973   if (Node->hasTemplateKeyword())
974     OS << "template ";
975   OS << Node->getNameInfo();
976   if (Node->hasExplicitTemplateArgs())
977     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
978 }
979 
980 void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
981   if (Node->getQualifier())
982     Node->getQualifier()->print(OS, Policy);
983   if (Node->hasTemplateKeyword())
984     OS << "template ";
985   OS << Node->getNameInfo();
986   if (Node->hasExplicitTemplateArgs())
987     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
988 }
989 
990 static bool isImplicitSelf(const Expr *E) {
991   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
992     if (const auto *PD = dyn_cast<ImplicitParamDecl>(DRE->getDecl())) {
993       if (PD->getParameterKind() == ImplicitParamDecl::ObjCSelf &&
994           DRE->getBeginLoc().isInvalid())
995         return true;
996     }
997   }
998   return false;
999 }
1000 
1001 void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
1002   if (Node->getBase()) {
1003     if (!Policy.SuppressImplicitBase ||
1004         !isImplicitSelf(Node->getBase()->IgnoreImpCasts())) {
1005       PrintExpr(Node->getBase());
1006       OS << (Node->isArrow() ? "->" : ".");
1007     }
1008   }
1009   OS << *Node->getDecl();
1010 }
1011 
1012 void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
1013   if (Node->isSuperReceiver())
1014     OS << "super.";
1015   else if (Node->isObjectReceiver() && Node->getBase()) {
1016     PrintExpr(Node->getBase());
1017     OS << ".";
1018   } else if (Node->isClassReceiver() && Node->getClassReceiver()) {
1019     OS << Node->getClassReceiver()->getName() << ".";
1020   }
1021 
1022   if (Node->isImplicitProperty()) {
1023     if (const auto *Getter = Node->getImplicitPropertyGetter())
1024       Getter->getSelector().print(OS);
1025     else
1026       OS << SelectorTable::getPropertyNameFromSetterSelector(
1027           Node->getImplicitPropertySetter()->getSelector());
1028   } else
1029     OS << Node->getExplicitProperty()->getName();
1030 }
1031 
1032 void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
1033   PrintExpr(Node->getBaseExpr());
1034   OS << "[";
1035   PrintExpr(Node->getKeyExpr());
1036   OS << "]";
1037 }
1038 
1039 void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
1040   OS << PredefinedExpr::getIdentKindName(Node->getIdentKind());
1041 }
1042 
1043 void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
1044   unsigned value = Node->getValue();
1045 
1046   switch (Node->getKind()) {
1047   case CharacterLiteral::Ascii: break; // no prefix.
1048   case CharacterLiteral::Wide:  OS << 'L'; break;
1049   case CharacterLiteral::UTF8:  OS << "u8"; break;
1050   case CharacterLiteral::UTF16: OS << 'u'; break;
1051   case CharacterLiteral::UTF32: OS << 'U'; break;
1052   }
1053 
1054   switch (value) {
1055   case '\\':
1056     OS << "'\\\\'";
1057     break;
1058   case '\'':
1059     OS << "'\\''";
1060     break;
1061   case '\a':
1062     // TODO: K&R: the meaning of '\\a' is different in traditional C
1063     OS << "'\\a'";
1064     break;
1065   case '\b':
1066     OS << "'\\b'";
1067     break;
1068   // Nonstandard escape sequence.
1069   /*case '\e':
1070     OS << "'\\e'";
1071     break;*/
1072   case '\f':
1073     OS << "'\\f'";
1074     break;
1075   case '\n':
1076     OS << "'\\n'";
1077     break;
1078   case '\r':
1079     OS << "'\\r'";
1080     break;
1081   case '\t':
1082     OS << "'\\t'";
1083     break;
1084   case '\v':
1085     OS << "'\\v'";
1086     break;
1087   default:
1088     // A character literal might be sign-extended, which
1089     // would result in an invalid \U escape sequence.
1090     // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1091     // are not correctly handled.
1092     if ((value & ~0xFFu) == ~0xFFu && Node->getKind() == CharacterLiteral::Ascii)
1093       value &= 0xFFu;
1094     if (value < 256 && isPrintable((unsigned char)value))
1095       OS << "'" << (char)value << "'";
1096     else if (value < 256)
1097       OS << "'\\x" << llvm::format("%02x", value) << "'";
1098     else if (value <= 0xFFFF)
1099       OS << "'\\u" << llvm::format("%04x", value) << "'";
1100     else
1101       OS << "'\\U" << llvm::format("%08x", value) << "'";
1102   }
1103 }
1104 
1105 /// Prints the given expression using the original source text. Returns true on
1106 /// success, false otherwise.
1107 static bool printExprAsWritten(raw_ostream &OS, Expr *E,
1108                                const ASTContext *Context) {
1109   if (!Context)
1110     return false;
1111   bool Invalid = false;
1112   StringRef Source = Lexer::getSourceText(
1113       CharSourceRange::getTokenRange(E->getSourceRange()),
1114       Context->getSourceManager(), Context->getLangOpts(), &Invalid);
1115   if (!Invalid) {
1116     OS << Source;
1117     return true;
1118   }
1119   return false;
1120 }
1121 
1122 void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
1123   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1124     return;
1125   bool isSigned = Node->getType()->isSignedIntegerType();
1126   OS << Node->getValue().toString(10, isSigned);
1127 
1128   // Emit suffixes.  Integer literals are always a builtin integer type.
1129   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1130   default: llvm_unreachable("Unexpected type for integer literal!");
1131   case BuiltinType::Char_S:
1132   case BuiltinType::Char_U:    OS << "i8"; break;
1133   case BuiltinType::UChar:     OS << "Ui8"; break;
1134   case BuiltinType::Short:     OS << "i16"; break;
1135   case BuiltinType::UShort:    OS << "Ui16"; break;
1136   case BuiltinType::Int:       break; // no suffix.
1137   case BuiltinType::UInt:      OS << 'U'; break;
1138   case BuiltinType::Long:      OS << 'L'; break;
1139   case BuiltinType::ULong:     OS << "UL"; break;
1140   case BuiltinType::LongLong:  OS << "LL"; break;
1141   case BuiltinType::ULongLong: OS << "ULL"; break;
1142   }
1143 }
1144 
1145 void StmtPrinter::VisitFixedPointLiteral(FixedPointLiteral *Node) {
1146   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1147     return;
1148   OS << Node->getValueAsString(/*Radix=*/10);
1149 
1150   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1151     default: llvm_unreachable("Unexpected type for fixed point literal!");
1152     case BuiltinType::ShortFract:   OS << "hr"; break;
1153     case BuiltinType::ShortAccum:   OS << "hk"; break;
1154     case BuiltinType::UShortFract:  OS << "uhr"; break;
1155     case BuiltinType::UShortAccum:  OS << "uhk"; break;
1156     case BuiltinType::Fract:        OS << "r"; break;
1157     case BuiltinType::Accum:        OS << "k"; break;
1158     case BuiltinType::UFract:       OS << "ur"; break;
1159     case BuiltinType::UAccum:       OS << "uk"; break;
1160     case BuiltinType::LongFract:    OS << "lr"; break;
1161     case BuiltinType::LongAccum:    OS << "lk"; break;
1162     case BuiltinType::ULongFract:   OS << "ulr"; break;
1163     case BuiltinType::ULongAccum:   OS << "ulk"; break;
1164   }
1165 }
1166 
1167 static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
1168                                  bool PrintSuffix) {
1169   SmallString<16> Str;
1170   Node->getValue().toString(Str);
1171   OS << Str;
1172   if (Str.find_first_not_of("-0123456789") == StringRef::npos)
1173     OS << '.'; // Trailing dot in order to separate from ints.
1174 
1175   if (!PrintSuffix)
1176     return;
1177 
1178   // Emit suffixes.  Float literals are always a builtin float type.
1179   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1180   default: llvm_unreachable("Unexpected type for float literal!");
1181   case BuiltinType::Half:       break; // FIXME: suffix?
1182   case BuiltinType::Double:     break; // no suffix.
1183   case BuiltinType::Float16:    OS << "F16"; break;
1184   case BuiltinType::Float:      OS << 'F'; break;
1185   case BuiltinType::LongDouble: OS << 'L'; break;
1186   case BuiltinType::Float128:   OS << 'Q'; break;
1187   }
1188 }
1189 
1190 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
1191   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1192     return;
1193   PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
1194 }
1195 
1196 void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
1197   PrintExpr(Node->getSubExpr());
1198   OS << "i";
1199 }
1200 
1201 void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
1202   Str->outputString(OS);
1203 }
1204 
1205 void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
1206   OS << "(";
1207   PrintExpr(Node->getSubExpr());
1208   OS << ")";
1209 }
1210 
1211 void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
1212   if (!Node->isPostfix()) {
1213     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1214 
1215     // Print a space if this is an "identifier operator" like __real, or if
1216     // it might be concatenated incorrectly like '+'.
1217     switch (Node->getOpcode()) {
1218     default: break;
1219     case UO_Real:
1220     case UO_Imag:
1221     case UO_Extension:
1222       OS << ' ';
1223       break;
1224     case UO_Plus:
1225     case UO_Minus:
1226       if (isa<UnaryOperator>(Node->getSubExpr()))
1227         OS << ' ';
1228       break;
1229     }
1230   }
1231   PrintExpr(Node->getSubExpr());
1232 
1233   if (Node->isPostfix())
1234     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1235 }
1236 
1237 void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
1238   OS << "__builtin_offsetof(";
1239   Node->getTypeSourceInfo()->getType().print(OS, Policy);
1240   OS << ", ";
1241   bool PrintedSomething = false;
1242   for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
1243     OffsetOfNode ON = Node->getComponent(i);
1244     if (ON.getKind() == OffsetOfNode::Array) {
1245       // Array node
1246       OS << "[";
1247       PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
1248       OS << "]";
1249       PrintedSomething = true;
1250       continue;
1251     }
1252 
1253     // Skip implicit base indirections.
1254     if (ON.getKind() == OffsetOfNode::Base)
1255       continue;
1256 
1257     // Field or identifier node.
1258     IdentifierInfo *Id = ON.getFieldName();
1259     if (!Id)
1260       continue;
1261 
1262     if (PrintedSomething)
1263       OS << ".";
1264     else
1265       PrintedSomething = true;
1266     OS << Id->getName();
1267   }
1268   OS << ")";
1269 }
1270 
1271 void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
1272   switch(Node->getKind()) {
1273   case UETT_SizeOf:
1274     OS << "sizeof";
1275     break;
1276   case UETT_AlignOf:
1277     if (Policy.Alignof)
1278       OS << "alignof";
1279     else if (Policy.UnderscoreAlignof)
1280       OS << "_Alignof";
1281     else
1282       OS << "__alignof";
1283     break;
1284   case UETT_PreferredAlignOf:
1285     OS << "__alignof";
1286     break;
1287   case UETT_VecStep:
1288     OS << "vec_step";
1289     break;
1290   case UETT_OpenMPRequiredSimdAlign:
1291     OS << "__builtin_omp_required_simd_align";
1292     break;
1293   }
1294   if (Node->isArgumentType()) {
1295     OS << '(';
1296     Node->getArgumentType().print(OS, Policy);
1297     OS << ')';
1298   } else {
1299     OS << " ";
1300     PrintExpr(Node->getArgumentExpr());
1301   }
1302 }
1303 
1304 void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
1305   OS << "_Generic(";
1306   PrintExpr(Node->getControllingExpr());
1307   for (const GenericSelectionExpr::Association Assoc : Node->associations()) {
1308     OS << ", ";
1309     QualType T = Assoc.getType();
1310     if (T.isNull())
1311       OS << "default";
1312     else
1313       T.print(OS, Policy);
1314     OS << ": ";
1315     PrintExpr(Assoc.getAssociationExpr());
1316   }
1317   OS << ")";
1318 }
1319 
1320 void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
1321   PrintExpr(Node->getLHS());
1322   OS << "[";
1323   PrintExpr(Node->getRHS());
1324   OS << "]";
1325 }
1326 
1327 void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) {
1328   PrintExpr(Node->getBase());
1329   OS << "[";
1330   if (Node->getLowerBound())
1331     PrintExpr(Node->getLowerBound());
1332   if (Node->getColonLoc().isValid()) {
1333     OS << ":";
1334     if (Node->getLength())
1335       PrintExpr(Node->getLength());
1336   }
1337   OS << "]";
1338 }
1339 
1340 void StmtPrinter::PrintCallArgs(CallExpr *Call) {
1341   for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
1342     if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
1343       // Don't print any defaulted arguments
1344       break;
1345     }
1346 
1347     if (i) OS << ", ";
1348     PrintExpr(Call->getArg(i));
1349   }
1350 }
1351 
1352 void StmtPrinter::VisitCallExpr(CallExpr *Call) {
1353   PrintExpr(Call->getCallee());
1354   OS << "(";
1355   PrintCallArgs(Call);
1356   OS << ")";
1357 }
1358 
1359 static bool isImplicitThis(const Expr *E) {
1360   if (const auto *TE = dyn_cast<CXXThisExpr>(E))
1361     return TE->isImplicit();
1362   return false;
1363 }
1364 
1365 void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
1366   if (!Policy.SuppressImplicitBase || !isImplicitThis(Node->getBase())) {
1367     PrintExpr(Node->getBase());
1368 
1369     auto *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
1370     FieldDecl *ParentDecl =
1371         ParentMember ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl())
1372                      : nullptr;
1373 
1374     if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
1375       OS << (Node->isArrow() ? "->" : ".");
1376   }
1377 
1378   if (auto *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
1379     if (FD->isAnonymousStructOrUnion())
1380       return;
1381 
1382   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1383     Qualifier->print(OS, Policy);
1384   if (Node->hasTemplateKeyword())
1385     OS << "template ";
1386   OS << Node->getMemberNameInfo();
1387   if (Node->hasExplicitTemplateArgs())
1388     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
1389 }
1390 
1391 void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
1392   PrintExpr(Node->getBase());
1393   OS << (Node->isArrow() ? "->isa" : ".isa");
1394 }
1395 
1396 void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
1397   PrintExpr(Node->getBase());
1398   OS << ".";
1399   OS << Node->getAccessor().getName();
1400 }
1401 
1402 void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
1403   OS << '(';
1404   Node->getTypeAsWritten().print(OS, Policy);
1405   OS << ')';
1406   PrintExpr(Node->getSubExpr());
1407 }
1408 
1409 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
1410   OS << '(';
1411   Node->getType().print(OS, Policy);
1412   OS << ')';
1413   PrintExpr(Node->getInitializer());
1414 }
1415 
1416 void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
1417   // No need to print anything, simply forward to the subexpression.
1418   PrintExpr(Node->getSubExpr());
1419 }
1420 
1421 void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
1422   PrintExpr(Node->getLHS());
1423   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1424   PrintExpr(Node->getRHS());
1425 }
1426 
1427 void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
1428   PrintExpr(Node->getLHS());
1429   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1430   PrintExpr(Node->getRHS());
1431 }
1432 
1433 void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
1434   PrintExpr(Node->getCond());
1435   OS << " ? ";
1436   PrintExpr(Node->getLHS());
1437   OS << " : ";
1438   PrintExpr(Node->getRHS());
1439 }
1440 
1441 // GNU extensions.
1442 
1443 void
1444 StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
1445   PrintExpr(Node->getCommon());
1446   OS << " ?: ";
1447   PrintExpr(Node->getFalseExpr());
1448 }
1449 
1450 void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
1451   OS << "&&" << Node->getLabel()->getName();
1452 }
1453 
1454 void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
1455   OS << "(";
1456   PrintRawCompoundStmt(E->getSubStmt());
1457   OS << ")";
1458 }
1459 
1460 void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
1461   OS << "__builtin_choose_expr(";
1462   PrintExpr(Node->getCond());
1463   OS << ", ";
1464   PrintExpr(Node->getLHS());
1465   OS << ", ";
1466   PrintExpr(Node->getRHS());
1467   OS << ")";
1468 }
1469 
1470 void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1471   OS << "__null";
1472 }
1473 
1474 void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1475   OS << "__builtin_shufflevector(";
1476   for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
1477     if (i) OS << ", ";
1478     PrintExpr(Node->getExpr(i));
1479   }
1480   OS << ")";
1481 }
1482 
1483 void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) {
1484   OS << "__builtin_convertvector(";
1485   PrintExpr(Node->getSrcExpr());
1486   OS << ", ";
1487   Node->getType().print(OS, Policy);
1488   OS << ")";
1489 }
1490 
1491 void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1492   if (Node->getSyntacticForm()) {
1493     Visit(Node->getSyntacticForm());
1494     return;
1495   }
1496 
1497   OS << "{";
1498   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1499     if (i) OS << ", ";
1500     if (Node->getInit(i))
1501       PrintExpr(Node->getInit(i));
1502     else
1503       OS << "{}";
1504   }
1505   OS << "}";
1506 }
1507 
1508 void StmtPrinter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *Node) {
1509   // There's no way to express this expression in any of our supported
1510   // languages, so just emit something terse and (hopefully) clear.
1511   OS << "{";
1512   PrintExpr(Node->getSubExpr());
1513   OS << "}";
1514 }
1515 
1516 void StmtPrinter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *Node) {
1517   OS << "*";
1518 }
1519 
1520 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1521   OS << "(";
1522   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1523     if (i) OS << ", ";
1524     PrintExpr(Node->getExpr(i));
1525   }
1526   OS << ")";
1527 }
1528 
1529 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1530   bool NeedsEquals = true;
1531   for (const DesignatedInitExpr::Designator &D : Node->designators()) {
1532     if (D.isFieldDesignator()) {
1533       if (D.getDotLoc().isInvalid()) {
1534         if (IdentifierInfo *II = D.getFieldName()) {
1535           OS << II->getName() << ":";
1536           NeedsEquals = false;
1537         }
1538       } else {
1539         OS << "." << D.getFieldName()->getName();
1540       }
1541     } else {
1542       OS << "[";
1543       if (D.isArrayDesignator()) {
1544         PrintExpr(Node->getArrayIndex(D));
1545       } else {
1546         PrintExpr(Node->getArrayRangeStart(D));
1547         OS << " ... ";
1548         PrintExpr(Node->getArrayRangeEnd(D));
1549       }
1550       OS << "]";
1551     }
1552   }
1553 
1554   if (NeedsEquals)
1555     OS << " = ";
1556   else
1557     OS << " ";
1558   PrintExpr(Node->getInit());
1559 }
1560 
1561 void StmtPrinter::VisitDesignatedInitUpdateExpr(
1562     DesignatedInitUpdateExpr *Node) {
1563   OS << "{";
1564   OS << "/*base*/";
1565   PrintExpr(Node->getBase());
1566   OS << ", ";
1567 
1568   OS << "/*updater*/";
1569   PrintExpr(Node->getUpdater());
1570   OS << "}";
1571 }
1572 
1573 void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) {
1574   OS << "/*no init*/";
1575 }
1576 
1577 void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1578   if (Node->getType()->getAsCXXRecordDecl()) {
1579     OS << "/*implicit*/";
1580     Node->getType().print(OS, Policy);
1581     OS << "()";
1582   } else {
1583     OS << "/*implicit*/(";
1584     Node->getType().print(OS, Policy);
1585     OS << ')';
1586     if (Node->getType()->isRecordType())
1587       OS << "{}";
1588     else
1589       OS << 0;
1590   }
1591 }
1592 
1593 void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1594   OS << "__builtin_va_arg(";
1595   PrintExpr(Node->getSubExpr());
1596   OS << ", ";
1597   Node->getType().print(OS, Policy);
1598   OS << ")";
1599 }
1600 
1601 void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1602   PrintExpr(Node->getSyntacticForm());
1603 }
1604 
1605 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1606   const char *Name = nullptr;
1607   switch (Node->getOp()) {
1608 #define BUILTIN(ID, TYPE, ATTRS)
1609 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1610   case AtomicExpr::AO ## ID: \
1611     Name = #ID "("; \
1612     break;
1613 #include "clang/Basic/Builtins.def"
1614   }
1615   OS << Name;
1616 
1617   // AtomicExpr stores its subexpressions in a permuted order.
1618   PrintExpr(Node->getPtr());
1619   if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1620       Node->getOp() != AtomicExpr::AO__atomic_load_n &&
1621       Node->getOp() != AtomicExpr::AO__opencl_atomic_load) {
1622     OS << ", ";
1623     PrintExpr(Node->getVal1());
1624   }
1625   if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1626       Node->isCmpXChg()) {
1627     OS << ", ";
1628     PrintExpr(Node->getVal2());
1629   }
1630   if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1631       Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1632     OS << ", ";
1633     PrintExpr(Node->getWeak());
1634   }
1635   if (Node->getOp() != AtomicExpr::AO__c11_atomic_init &&
1636       Node->getOp() != AtomicExpr::AO__opencl_atomic_init) {
1637     OS << ", ";
1638     PrintExpr(Node->getOrder());
1639   }
1640   if (Node->isCmpXChg()) {
1641     OS << ", ";
1642     PrintExpr(Node->getOrderFail());
1643   }
1644   OS << ")";
1645 }
1646 
1647 // C++
1648 void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1649   OverloadedOperatorKind Kind = Node->getOperator();
1650   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1651     if (Node->getNumArgs() == 1) {
1652       OS << getOperatorSpelling(Kind) << ' ';
1653       PrintExpr(Node->getArg(0));
1654     } else {
1655       PrintExpr(Node->getArg(0));
1656       OS << ' ' << getOperatorSpelling(Kind);
1657     }
1658   } else if (Kind == OO_Arrow) {
1659     PrintExpr(Node->getArg(0));
1660   } else if (Kind == OO_Call) {
1661     PrintExpr(Node->getArg(0));
1662     OS << '(';
1663     for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1664       if (ArgIdx > 1)
1665         OS << ", ";
1666       if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1667         PrintExpr(Node->getArg(ArgIdx));
1668     }
1669     OS << ')';
1670   } else if (Kind == OO_Subscript) {
1671     PrintExpr(Node->getArg(0));
1672     OS << '[';
1673     PrintExpr(Node->getArg(1));
1674     OS << ']';
1675   } else if (Node->getNumArgs() == 1) {
1676     OS << getOperatorSpelling(Kind) << ' ';
1677     PrintExpr(Node->getArg(0));
1678   } else if (Node->getNumArgs() == 2) {
1679     PrintExpr(Node->getArg(0));
1680     OS << ' ' << getOperatorSpelling(Kind) << ' ';
1681     PrintExpr(Node->getArg(1));
1682   } else {
1683     llvm_unreachable("unknown overloaded operator");
1684   }
1685 }
1686 
1687 void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1688   // If we have a conversion operator call only print the argument.
1689   CXXMethodDecl *MD = Node->getMethodDecl();
1690   if (MD && isa<CXXConversionDecl>(MD)) {
1691     PrintExpr(Node->getImplicitObjectArgument());
1692     return;
1693   }
1694   VisitCallExpr(cast<CallExpr>(Node));
1695 }
1696 
1697 void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1698   PrintExpr(Node->getCallee());
1699   OS << "<<<";
1700   PrintCallArgs(Node->getConfig());
1701   OS << ">>>(";
1702   PrintCallArgs(Node);
1703   OS << ")";
1704 }
1705 
1706 void StmtPrinter::VisitCXXRewrittenBinaryOperator(
1707     CXXRewrittenBinaryOperator *Node) {
1708   CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
1709       Node->getDecomposedForm();
1710   PrintExpr(const_cast<Expr*>(Decomposed.LHS));
1711   OS << ' ' << BinaryOperator::getOpcodeStr(Decomposed.Opcode) << ' ';
1712   PrintExpr(const_cast<Expr*>(Decomposed.RHS));
1713 }
1714 
1715 void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1716   OS << Node->getCastName() << '<';
1717   Node->getTypeAsWritten().print(OS, Policy);
1718   OS << ">(";
1719   PrintExpr(Node->getSubExpr());
1720   OS << ")";
1721 }
1722 
1723 void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1724   VisitCXXNamedCastExpr(Node);
1725 }
1726 
1727 void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1728   VisitCXXNamedCastExpr(Node);
1729 }
1730 
1731 void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1732   VisitCXXNamedCastExpr(Node);
1733 }
1734 
1735 void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1736   VisitCXXNamedCastExpr(Node);
1737 }
1738 
1739 void StmtPrinter::VisitBuiltinBitCastExpr(BuiltinBitCastExpr *Node) {
1740   OS << "__builtin_bit_cast(";
1741   Node->getTypeInfoAsWritten()->getType().print(OS, Policy);
1742   OS << ", ";
1743   PrintExpr(Node->getSubExpr());
1744   OS << ")";
1745 }
1746 
1747 void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1748   OS << "typeid(";
1749   if (Node->isTypeOperand()) {
1750     Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1751   } else {
1752     PrintExpr(Node->getExprOperand());
1753   }
1754   OS << ")";
1755 }
1756 
1757 void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1758   OS << "__uuidof(";
1759   if (Node->isTypeOperand()) {
1760     Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1761   } else {
1762     PrintExpr(Node->getExprOperand());
1763   }
1764   OS << ")";
1765 }
1766 
1767 void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
1768   PrintExpr(Node->getBaseExpr());
1769   if (Node->isArrow())
1770     OS << "->";
1771   else
1772     OS << ".";
1773   if (NestedNameSpecifier *Qualifier =
1774       Node->getQualifierLoc().getNestedNameSpecifier())
1775     Qualifier->print(OS, Policy);
1776   OS << Node->getPropertyDecl()->getDeclName();
1777 }
1778 
1779 void StmtPrinter::VisitMSPropertySubscriptExpr(MSPropertySubscriptExpr *Node) {
1780   PrintExpr(Node->getBase());
1781   OS << "[";
1782   PrintExpr(Node->getIdx());
1783   OS << "]";
1784 }
1785 
1786 void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1787   switch (Node->getLiteralOperatorKind()) {
1788   case UserDefinedLiteral::LOK_Raw:
1789     OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1790     break;
1791   case UserDefinedLiteral::LOK_Template: {
1792     const auto *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1793     const TemplateArgumentList *Args =
1794       cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1795     assert(Args);
1796 
1797     if (Args->size() != 1) {
1798       OS << "operator\"\"" << Node->getUDSuffix()->getName();
1799       printTemplateArgumentList(OS, Args->asArray(), Policy);
1800       OS << "()";
1801       return;
1802     }
1803 
1804     const TemplateArgument &Pack = Args->get(0);
1805     for (const auto &P : Pack.pack_elements()) {
1806       char C = (char)P.getAsIntegral().getZExtValue();
1807       OS << C;
1808     }
1809     break;
1810   }
1811   case UserDefinedLiteral::LOK_Integer: {
1812     // Print integer literal without suffix.
1813     const auto *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1814     OS << Int->getValue().toString(10, /*isSigned*/false);
1815     break;
1816   }
1817   case UserDefinedLiteral::LOK_Floating: {
1818     // Print floating literal without suffix.
1819     auto *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1820     PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1821     break;
1822   }
1823   case UserDefinedLiteral::LOK_String:
1824   case UserDefinedLiteral::LOK_Character:
1825     PrintExpr(Node->getCookedLiteral());
1826     break;
1827   }
1828   OS << Node->getUDSuffix()->getName();
1829 }
1830 
1831 void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1832   OS << (Node->getValue() ? "true" : "false");
1833 }
1834 
1835 void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1836   OS << "nullptr";
1837 }
1838 
1839 void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1840   OS << "this";
1841 }
1842 
1843 void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1844   if (!Node->getSubExpr())
1845     OS << "throw";
1846   else {
1847     OS << "throw ";
1848     PrintExpr(Node->getSubExpr());
1849   }
1850 }
1851 
1852 void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1853   // Nothing to print: we picked up the default argument.
1854 }
1855 
1856 void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
1857   // Nothing to print: we picked up the default initializer.
1858 }
1859 
1860 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1861   Node->getType().print(OS, Policy);
1862   // If there are no parens, this is list-initialization, and the braces are
1863   // part of the syntax of the inner construct.
1864   if (Node->getLParenLoc().isValid())
1865     OS << "(";
1866   PrintExpr(Node->getSubExpr());
1867   if (Node->getLParenLoc().isValid())
1868     OS << ")";
1869 }
1870 
1871 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1872   PrintExpr(Node->getSubExpr());
1873 }
1874 
1875 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1876   Node->getType().print(OS, Policy);
1877   if (Node->isStdInitListInitialization())
1878     /* Nothing to do; braces are part of creating the std::initializer_list. */;
1879   else if (Node->isListInitialization())
1880     OS << "{";
1881   else
1882     OS << "(";
1883   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1884                                          ArgEnd = Node->arg_end();
1885        Arg != ArgEnd; ++Arg) {
1886     if ((*Arg)->isDefaultArgument())
1887       break;
1888     if (Arg != Node->arg_begin())
1889       OS << ", ";
1890     PrintExpr(*Arg);
1891   }
1892   if (Node->isStdInitListInitialization())
1893     /* See above. */;
1894   else if (Node->isListInitialization())
1895     OS << "}";
1896   else
1897     OS << ")";
1898 }
1899 
1900 void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1901   OS << '[';
1902   bool NeedComma = false;
1903   switch (Node->getCaptureDefault()) {
1904   case LCD_None:
1905     break;
1906 
1907   case LCD_ByCopy:
1908     OS << '=';
1909     NeedComma = true;
1910     break;
1911 
1912   case LCD_ByRef:
1913     OS << '&';
1914     NeedComma = true;
1915     break;
1916   }
1917   for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1918                                  CEnd = Node->explicit_capture_end();
1919        C != CEnd;
1920        ++C) {
1921     if (C->capturesVLAType())
1922       continue;
1923 
1924     if (NeedComma)
1925       OS << ", ";
1926     NeedComma = true;
1927 
1928     switch (C->getCaptureKind()) {
1929     case LCK_This:
1930       OS << "this";
1931       break;
1932 
1933     case LCK_StarThis:
1934       OS << "*this";
1935       break;
1936 
1937     case LCK_ByRef:
1938       if (Node->getCaptureDefault() != LCD_ByRef || Node->isInitCapture(C))
1939         OS << '&';
1940       OS << C->getCapturedVar()->getName();
1941       break;
1942 
1943     case LCK_ByCopy:
1944       OS << C->getCapturedVar()->getName();
1945       break;
1946 
1947     case LCK_VLAType:
1948       llvm_unreachable("VLA type in explicit captures.");
1949     }
1950 
1951     if (C->isPackExpansion())
1952       OS << "...";
1953 
1954     if (Node->isInitCapture(C))
1955       PrintExpr(C->getCapturedVar()->getInit());
1956   }
1957   OS << ']';
1958 
1959   if (!Node->getExplicitTemplateParameters().empty()) {
1960     Node->getTemplateParameterList()->print(
1961         OS, Node->getLambdaClass()->getASTContext(),
1962         /*OmitTemplateKW*/true);
1963   }
1964 
1965   if (Node->hasExplicitParameters()) {
1966     OS << '(';
1967     CXXMethodDecl *Method = Node->getCallOperator();
1968     NeedComma = false;
1969     for (const auto *P : Method->parameters()) {
1970       if (NeedComma) {
1971         OS << ", ";
1972       } else {
1973         NeedComma = true;
1974       }
1975       std::string ParamStr = P->getNameAsString();
1976       P->getOriginalType().print(OS, Policy, ParamStr);
1977     }
1978     if (Method->isVariadic()) {
1979       if (NeedComma)
1980         OS << ", ";
1981       OS << "...";
1982     }
1983     OS << ')';
1984 
1985     if (Node->isMutable())
1986       OS << " mutable";
1987 
1988     auto *Proto = Method->getType()->castAs<FunctionProtoType>();
1989     Proto->printExceptionSpecification(OS, Policy);
1990 
1991     // FIXME: Attributes
1992 
1993     // Print the trailing return type if it was specified in the source.
1994     if (Node->hasExplicitResultType()) {
1995       OS << " -> ";
1996       Proto->getReturnType().print(OS, Policy);
1997     }
1998   }
1999 
2000   // Print the body.
2001   OS << ' ';
2002   if (Policy.TerseOutput)
2003     OS << "{}";
2004   else
2005     PrintRawCompoundStmt(Node->getBody());
2006 }
2007 
2008 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
2009   if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
2010     TSInfo->getType().print(OS, Policy);
2011   else
2012     Node->getType().print(OS, Policy);
2013   OS << "()";
2014 }
2015 
2016 void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
2017   if (E->isGlobalNew())
2018     OS << "::";
2019   OS << "new ";
2020   unsigned NumPlace = E->getNumPlacementArgs();
2021   if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
2022     OS << "(";
2023     PrintExpr(E->getPlacementArg(0));
2024     for (unsigned i = 1; i < NumPlace; ++i) {
2025       if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
2026         break;
2027       OS << ", ";
2028       PrintExpr(E->getPlacementArg(i));
2029     }
2030     OS << ") ";
2031   }
2032   if (E->isParenTypeId())
2033     OS << "(";
2034   std::string TypeS;
2035   if (Optional<Expr *> Size = E->getArraySize()) {
2036     llvm::raw_string_ostream s(TypeS);
2037     s << '[';
2038     if (*Size)
2039       (*Size)->printPretty(s, Helper, Policy);
2040     s << ']';
2041   }
2042   E->getAllocatedType().print(OS, Policy, TypeS);
2043   if (E->isParenTypeId())
2044     OS << ")";
2045 
2046   CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
2047   if (InitStyle) {
2048     if (InitStyle == CXXNewExpr::CallInit)
2049       OS << "(";
2050     PrintExpr(E->getInitializer());
2051     if (InitStyle == CXXNewExpr::CallInit)
2052       OS << ")";
2053   }
2054 }
2055 
2056 void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2057   if (E->isGlobalDelete())
2058     OS << "::";
2059   OS << "delete ";
2060   if (E->isArrayForm())
2061     OS << "[] ";
2062   PrintExpr(E->getArgument());
2063 }
2064 
2065 void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
2066   PrintExpr(E->getBase());
2067   if (E->isArrow())
2068     OS << "->";
2069   else
2070     OS << '.';
2071   if (E->getQualifier())
2072     E->getQualifier()->print(OS, Policy);
2073   OS << "~";
2074 
2075   if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
2076     OS << II->getName();
2077   else
2078     E->getDestroyedType().print(OS, Policy);
2079 }
2080 
2081 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
2082   if (E->isListInitialization() && !E->isStdInitListInitialization())
2083     OS << "{";
2084 
2085   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
2086     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
2087       // Don't print any defaulted arguments
2088       break;
2089     }
2090 
2091     if (i) OS << ", ";
2092     PrintExpr(E->getArg(i));
2093   }
2094 
2095   if (E->isListInitialization() && !E->isStdInitListInitialization())
2096     OS << "}";
2097 }
2098 
2099 void StmtPrinter::VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E) {
2100   // Parens are printed by the surrounding context.
2101   OS << "<forwarded>";
2102 }
2103 
2104 void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
2105   PrintExpr(E->getSubExpr());
2106 }
2107 
2108 void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
2109   // Just forward to the subexpression.
2110   PrintExpr(E->getSubExpr());
2111 }
2112 
2113 void
2114 StmtPrinter::VisitCXXUnresolvedConstructExpr(
2115                                            CXXUnresolvedConstructExpr *Node) {
2116   Node->getTypeAsWritten().print(OS, Policy);
2117   OS << "(";
2118   for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
2119                                              ArgEnd = Node->arg_end();
2120        Arg != ArgEnd; ++Arg) {
2121     if (Arg != Node->arg_begin())
2122       OS << ", ";
2123     PrintExpr(*Arg);
2124   }
2125   OS << ")";
2126 }
2127 
2128 void StmtPrinter::VisitCXXDependentScopeMemberExpr(
2129                                          CXXDependentScopeMemberExpr *Node) {
2130   if (!Node->isImplicitAccess()) {
2131     PrintExpr(Node->getBase());
2132     OS << (Node->isArrow() ? "->" : ".");
2133   }
2134   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2135     Qualifier->print(OS, Policy);
2136   if (Node->hasTemplateKeyword())
2137     OS << "template ";
2138   OS << Node->getMemberNameInfo();
2139   if (Node->hasExplicitTemplateArgs())
2140     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2141 }
2142 
2143 void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
2144   if (!Node->isImplicitAccess()) {
2145     PrintExpr(Node->getBase());
2146     OS << (Node->isArrow() ? "->" : ".");
2147   }
2148   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2149     Qualifier->print(OS, Policy);
2150   if (Node->hasTemplateKeyword())
2151     OS << "template ";
2152   OS << Node->getMemberNameInfo();
2153   if (Node->hasExplicitTemplateArgs())
2154     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2155 }
2156 
2157 static const char *getTypeTraitName(TypeTrait TT) {
2158   switch (TT) {
2159 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2160 case clang::UTT_##Name: return #Spelling;
2161 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2162 case clang::BTT_##Name: return #Spelling;
2163 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2164   case clang::TT_##Name: return #Spelling;
2165 #include "clang/Basic/TokenKinds.def"
2166   }
2167   llvm_unreachable("Type trait not covered by switch");
2168 }
2169 
2170 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
2171   switch (ATT) {
2172   case ATT_ArrayRank:        return "__array_rank";
2173   case ATT_ArrayExtent:      return "__array_extent";
2174   }
2175   llvm_unreachable("Array type trait not covered by switch");
2176 }
2177 
2178 static const char *getExpressionTraitName(ExpressionTrait ET) {
2179   switch (ET) {
2180   case ET_IsLValueExpr:      return "__is_lvalue_expr";
2181   case ET_IsRValueExpr:      return "__is_rvalue_expr";
2182   }
2183   llvm_unreachable("Expression type trait not covered by switch");
2184 }
2185 
2186 void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
2187   OS << getTypeTraitName(E->getTrait()) << "(";
2188   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
2189     if (I > 0)
2190       OS << ", ";
2191     E->getArg(I)->getType().print(OS, Policy);
2192   }
2193   OS << ")";
2194 }
2195 
2196 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2197   OS << getTypeTraitName(E->getTrait()) << '(';
2198   E->getQueriedType().print(OS, Policy);
2199   OS << ')';
2200 }
2201 
2202 void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2203   OS << getExpressionTraitName(E->getTrait()) << '(';
2204   PrintExpr(E->getQueriedExpression());
2205   OS << ')';
2206 }
2207 
2208 void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
2209   OS << "noexcept(";
2210   PrintExpr(E->getOperand());
2211   OS << ")";
2212 }
2213 
2214 void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
2215   PrintExpr(E->getPattern());
2216   OS << "...";
2217 }
2218 
2219 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2220   OS << "sizeof...(" << *E->getPack() << ")";
2221 }
2222 
2223 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
2224                                        SubstNonTypeTemplateParmPackExpr *Node) {
2225   OS << *Node->getParameterPack();
2226 }
2227 
2228 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
2229                                        SubstNonTypeTemplateParmExpr *Node) {
2230   Visit(Node->getReplacement());
2231 }
2232 
2233 void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
2234   OS << *E->getParameterPack();
2235 }
2236 
2237 void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
2238   PrintExpr(Node->getSubExpr());
2239 }
2240 
2241 void StmtPrinter::VisitCXXFoldExpr(CXXFoldExpr *E) {
2242   OS << "(";
2243   if (E->getLHS()) {
2244     PrintExpr(E->getLHS());
2245     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2246   }
2247   OS << "...";
2248   if (E->getRHS()) {
2249     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2250     PrintExpr(E->getRHS());
2251   }
2252   OS << ")";
2253 }
2254 
2255 void StmtPrinter::VisitConceptSpecializationExpr(ConceptSpecializationExpr *E) {
2256   NestedNameSpecifierLoc NNS = E->getNestedNameSpecifierLoc();
2257   if (NNS)
2258     NNS.getNestedNameSpecifier()->print(OS, Policy);
2259   if (E->getTemplateKWLoc().isValid())
2260     OS << "template ";
2261   OS << E->getFoundDecl()->getName();
2262   printTemplateArgumentList(OS, E->getTemplateArgsAsWritten()->arguments(),
2263                             Policy);
2264 }
2265 
2266 // C++ Coroutines TS
2267 
2268 void StmtPrinter::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) {
2269   Visit(S->getBody());
2270 }
2271 
2272 void StmtPrinter::VisitCoreturnStmt(CoreturnStmt *S) {
2273   OS << "co_return";
2274   if (S->getOperand()) {
2275     OS << " ";
2276     Visit(S->getOperand());
2277   }
2278   OS << ";";
2279 }
2280 
2281 void StmtPrinter::VisitCoawaitExpr(CoawaitExpr *S) {
2282   OS << "co_await ";
2283   PrintExpr(S->getOperand());
2284 }
2285 
2286 void StmtPrinter::VisitDependentCoawaitExpr(DependentCoawaitExpr *S) {
2287   OS << "co_await ";
2288   PrintExpr(S->getOperand());
2289 }
2290 
2291 void StmtPrinter::VisitCoyieldExpr(CoyieldExpr *S) {
2292   OS << "co_yield ";
2293   PrintExpr(S->getOperand());
2294 }
2295 
2296 // Obj-C
2297 
2298 void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
2299   OS << "@";
2300   VisitStringLiteral(Node->getString());
2301 }
2302 
2303 void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
2304   OS << "@";
2305   Visit(E->getSubExpr());
2306 }
2307 
2308 void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
2309   OS << "@[ ";
2310   ObjCArrayLiteral::child_range Ch = E->children();
2311   for (auto I = Ch.begin(), E = Ch.end(); I != E; ++I) {
2312     if (I != Ch.begin())
2313       OS << ", ";
2314     Visit(*I);
2315   }
2316   OS << " ]";
2317 }
2318 
2319 void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
2320   OS << "@{ ";
2321   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
2322     if (I > 0)
2323       OS << ", ";
2324 
2325     ObjCDictionaryElement Element = E->getKeyValueElement(I);
2326     Visit(Element.Key);
2327     OS << " : ";
2328     Visit(Element.Value);
2329     if (Element.isPackExpansion())
2330       OS << "...";
2331   }
2332   OS << " }";
2333 }
2334 
2335 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
2336   OS << "@encode(";
2337   Node->getEncodedType().print(OS, Policy);
2338   OS << ')';
2339 }
2340 
2341 void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
2342   OS << "@selector(";
2343   Node->getSelector().print(OS);
2344   OS << ')';
2345 }
2346 
2347 void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
2348   OS << "@protocol(" << *Node->getProtocol() << ')';
2349 }
2350 
2351 void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
2352   OS << "[";
2353   switch (Mess->getReceiverKind()) {
2354   case ObjCMessageExpr::Instance:
2355     PrintExpr(Mess->getInstanceReceiver());
2356     break;
2357 
2358   case ObjCMessageExpr::Class:
2359     Mess->getClassReceiver().print(OS, Policy);
2360     break;
2361 
2362   case ObjCMessageExpr::SuperInstance:
2363   case ObjCMessageExpr::SuperClass:
2364     OS << "Super";
2365     break;
2366   }
2367 
2368   OS << ' ';
2369   Selector selector = Mess->getSelector();
2370   if (selector.isUnarySelector()) {
2371     OS << selector.getNameForSlot(0);
2372   } else {
2373     for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
2374       if (i < selector.getNumArgs()) {
2375         if (i > 0) OS << ' ';
2376         if (selector.getIdentifierInfoForSlot(i))
2377           OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
2378         else
2379            OS << ":";
2380       }
2381       else OS << ", "; // Handle variadic methods.
2382 
2383       PrintExpr(Mess->getArg(i));
2384     }
2385   }
2386   OS << "]";
2387 }
2388 
2389 void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
2390   OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
2391 }
2392 
2393 void
2394 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
2395   PrintExpr(E->getSubExpr());
2396 }
2397 
2398 void
2399 StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
2400   OS << '(' << E->getBridgeKindName();
2401   E->getType().print(OS, Policy);
2402   OS << ')';
2403   PrintExpr(E->getSubExpr());
2404 }
2405 
2406 void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
2407   BlockDecl *BD = Node->getBlockDecl();
2408   OS << "^";
2409 
2410   const FunctionType *AFT = Node->getFunctionType();
2411 
2412   if (isa<FunctionNoProtoType>(AFT)) {
2413     OS << "()";
2414   } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
2415     OS << '(';
2416     for (BlockDecl::param_iterator AI = BD->param_begin(),
2417          E = BD->param_end(); AI != E; ++AI) {
2418       if (AI != BD->param_begin()) OS << ", ";
2419       std::string ParamStr = (*AI)->getNameAsString();
2420       (*AI)->getType().print(OS, Policy, ParamStr);
2421     }
2422 
2423     const auto *FT = cast<FunctionProtoType>(AFT);
2424     if (FT->isVariadic()) {
2425       if (!BD->param_empty()) OS << ", ";
2426       OS << "...";
2427     }
2428     OS << ')';
2429   }
2430   OS << "{ }";
2431 }
2432 
2433 void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
2434   PrintExpr(Node->getSourceExpr());
2435 }
2436 
2437 void StmtPrinter::VisitTypoExpr(TypoExpr *Node) {
2438   // TODO: Print something reasonable for a TypoExpr, if necessary.
2439   llvm_unreachable("Cannot print TypoExpr nodes");
2440 }
2441 
2442 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
2443   OS << "__builtin_astype(";
2444   PrintExpr(Node->getSrcExpr());
2445   OS << ", ";
2446   Node->getType().print(OS, Policy);
2447   OS << ")";
2448 }
2449 
2450 //===----------------------------------------------------------------------===//
2451 // Stmt method implementations
2452 //===----------------------------------------------------------------------===//
2453 
2454 void Stmt::dumpPretty(const ASTContext &Context) const {
2455   printPretty(llvm::errs(), nullptr, PrintingPolicy(Context.getLangOpts()));
2456 }
2457 
2458 void Stmt::printPretty(raw_ostream &Out, PrinterHelper *Helper,
2459                        const PrintingPolicy &Policy, unsigned Indentation,
2460                        StringRef NL, const ASTContext *Context) const {
2461   StmtPrinter P(Out, Helper, Policy, Indentation, NL, Context);
2462   P.Visit(const_cast<Stmt *>(this));
2463 }
2464 
2465 void Stmt::printJson(raw_ostream &Out, PrinterHelper *Helper,
2466                      const PrintingPolicy &Policy, bool AddQuotes) const {
2467   std::string Buf;
2468   llvm::raw_string_ostream TempOut(Buf);
2469 
2470   printPretty(TempOut, Helper, Policy);
2471 
2472   Out << JsonFormat(TempOut.str(), AddQuotes);
2473 }
2474 
2475 //===----------------------------------------------------------------------===//
2476 // PrinterHelper
2477 //===----------------------------------------------------------------------===//
2478 
2479 // Implement virtual destructor.
2480 PrinterHelper::~PrinterHelper() = default;
2481