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);
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::VisitOMPDistributeDirective(OMPDistributeDirective *Node) {
833   Indent() << "#pragma omp distribute";
834   PrintOMPExecutableDirective(Node);
835 }
836 
837 void StmtPrinter::VisitOMPTargetUpdateDirective(
838     OMPTargetUpdateDirective *Node) {
839   Indent() << "#pragma omp target update";
840   PrintOMPExecutableDirective(Node, /*ForceNoStmt=*/true);
841 }
842 
843 void StmtPrinter::VisitOMPDistributeParallelForDirective(
844     OMPDistributeParallelForDirective *Node) {
845   Indent() << "#pragma omp distribute parallel for";
846   PrintOMPExecutableDirective(Node);
847 }
848 
849 void StmtPrinter::VisitOMPDistributeParallelForSimdDirective(
850     OMPDistributeParallelForSimdDirective *Node) {
851   Indent() << "#pragma omp distribute parallel for simd";
852   PrintOMPExecutableDirective(Node);
853 }
854 
855 void StmtPrinter::VisitOMPDistributeSimdDirective(
856     OMPDistributeSimdDirective *Node) {
857   Indent() << "#pragma omp distribute simd";
858   PrintOMPExecutableDirective(Node);
859 }
860 
861 void StmtPrinter::VisitOMPTargetParallelForSimdDirective(
862     OMPTargetParallelForSimdDirective *Node) {
863   Indent() << "#pragma omp target parallel for simd";
864   PrintOMPExecutableDirective(Node);
865 }
866 
867 void StmtPrinter::VisitOMPTargetSimdDirective(OMPTargetSimdDirective *Node) {
868   Indent() << "#pragma omp target simd";
869   PrintOMPExecutableDirective(Node);
870 }
871 
872 void StmtPrinter::VisitOMPTeamsDistributeDirective(
873     OMPTeamsDistributeDirective *Node) {
874   Indent() << "#pragma omp teams distribute";
875   PrintOMPExecutableDirective(Node);
876 }
877 
878 void StmtPrinter::VisitOMPTeamsDistributeSimdDirective(
879     OMPTeamsDistributeSimdDirective *Node) {
880   Indent() << "#pragma omp teams distribute simd";
881   PrintOMPExecutableDirective(Node);
882 }
883 
884 void StmtPrinter::VisitOMPTeamsDistributeParallelForSimdDirective(
885     OMPTeamsDistributeParallelForSimdDirective *Node) {
886   Indent() << "#pragma omp teams distribute parallel for simd";
887   PrintOMPExecutableDirective(Node);
888 }
889 
890 void StmtPrinter::VisitOMPTeamsDistributeParallelForDirective(
891     OMPTeamsDistributeParallelForDirective *Node) {
892   Indent() << "#pragma omp teams distribute parallel for";
893   PrintOMPExecutableDirective(Node);
894 }
895 
896 void StmtPrinter::VisitOMPTargetTeamsDirective(OMPTargetTeamsDirective *Node) {
897   Indent() << "#pragma omp target teams";
898   PrintOMPExecutableDirective(Node);
899 }
900 
901 void StmtPrinter::VisitOMPTargetTeamsDistributeDirective(
902     OMPTargetTeamsDistributeDirective *Node) {
903   Indent() << "#pragma omp target teams distribute";
904   PrintOMPExecutableDirective(Node);
905 }
906 
907 void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForDirective(
908     OMPTargetTeamsDistributeParallelForDirective *Node) {
909   Indent() << "#pragma omp target teams distribute parallel for";
910   PrintOMPExecutableDirective(Node);
911 }
912 
913 void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
914     OMPTargetTeamsDistributeParallelForSimdDirective *Node) {
915   Indent() << "#pragma omp target teams distribute parallel for simd";
916   PrintOMPExecutableDirective(Node);
917 }
918 
919 void StmtPrinter::VisitOMPTargetTeamsDistributeSimdDirective(
920     OMPTargetTeamsDistributeSimdDirective *Node) {
921   Indent() << "#pragma omp target teams distribute simd";
922   PrintOMPExecutableDirective(Node);
923 }
924 
925 //===----------------------------------------------------------------------===//
926 //  Expr printing methods.
927 //===----------------------------------------------------------------------===//
928 
929 void StmtPrinter::VisitSourceLocExpr(SourceLocExpr *Node) {
930   OS << Node->getBuiltinStr() << "()";
931 }
932 
933 void StmtPrinter::VisitConstantExpr(ConstantExpr *Node) {
934   PrintExpr(Node->getSubExpr());
935 }
936 
937 void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
938   if (const auto *OCED = dyn_cast<OMPCapturedExprDecl>(Node->getDecl())) {
939     OCED->getInit()->IgnoreImpCasts()->printPretty(OS, nullptr, Policy);
940     return;
941   }
942   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
943     Qualifier->print(OS, Policy);
944   if (Node->hasTemplateKeyword())
945     OS << "template ";
946   OS << Node->getNameInfo();
947   if (Node->hasExplicitTemplateArgs())
948     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
949 }
950 
951 void StmtPrinter::VisitDependentScopeDeclRefExpr(
952                                            DependentScopeDeclRefExpr *Node) {
953   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
954     Qualifier->print(OS, Policy);
955   if (Node->hasTemplateKeyword())
956     OS << "template ";
957   OS << Node->getNameInfo();
958   if (Node->hasExplicitTemplateArgs())
959     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
960 }
961 
962 void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
963   if (Node->getQualifier())
964     Node->getQualifier()->print(OS, Policy);
965   if (Node->hasTemplateKeyword())
966     OS << "template ";
967   OS << Node->getNameInfo();
968   if (Node->hasExplicitTemplateArgs())
969     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
970 }
971 
972 static bool isImplicitSelf(const Expr *E) {
973   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
974     if (const auto *PD = dyn_cast<ImplicitParamDecl>(DRE->getDecl())) {
975       if (PD->getParameterKind() == ImplicitParamDecl::ObjCSelf &&
976           DRE->getBeginLoc().isInvalid())
977         return true;
978     }
979   }
980   return false;
981 }
982 
983 void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
984   if (Node->getBase()) {
985     if (!Policy.SuppressImplicitBase ||
986         !isImplicitSelf(Node->getBase()->IgnoreImpCasts())) {
987       PrintExpr(Node->getBase());
988       OS << (Node->isArrow() ? "->" : ".");
989     }
990   }
991   OS << *Node->getDecl();
992 }
993 
994 void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
995   if (Node->isSuperReceiver())
996     OS << "super.";
997   else if (Node->isObjectReceiver() && Node->getBase()) {
998     PrintExpr(Node->getBase());
999     OS << ".";
1000   } else if (Node->isClassReceiver() && Node->getClassReceiver()) {
1001     OS << Node->getClassReceiver()->getName() << ".";
1002   }
1003 
1004   if (Node->isImplicitProperty()) {
1005     if (const auto *Getter = Node->getImplicitPropertyGetter())
1006       Getter->getSelector().print(OS);
1007     else
1008       OS << SelectorTable::getPropertyNameFromSetterSelector(
1009           Node->getImplicitPropertySetter()->getSelector());
1010   } else
1011     OS << Node->getExplicitProperty()->getName();
1012 }
1013 
1014 void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
1015   PrintExpr(Node->getBaseExpr());
1016   OS << "[";
1017   PrintExpr(Node->getKeyExpr());
1018   OS << "]";
1019 }
1020 
1021 void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
1022   OS << PredefinedExpr::getIdentKindName(Node->getIdentKind());
1023 }
1024 
1025 void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
1026   unsigned value = Node->getValue();
1027 
1028   switch (Node->getKind()) {
1029   case CharacterLiteral::Ascii: break; // no prefix.
1030   case CharacterLiteral::Wide:  OS << 'L'; break;
1031   case CharacterLiteral::UTF8:  OS << "u8"; break;
1032   case CharacterLiteral::UTF16: OS << 'u'; break;
1033   case CharacterLiteral::UTF32: OS << 'U'; break;
1034   }
1035 
1036   switch (value) {
1037   case '\\':
1038     OS << "'\\\\'";
1039     break;
1040   case '\'':
1041     OS << "'\\''";
1042     break;
1043   case '\a':
1044     // TODO: K&R: the meaning of '\\a' is different in traditional C
1045     OS << "'\\a'";
1046     break;
1047   case '\b':
1048     OS << "'\\b'";
1049     break;
1050   // Nonstandard escape sequence.
1051   /*case '\e':
1052     OS << "'\\e'";
1053     break;*/
1054   case '\f':
1055     OS << "'\\f'";
1056     break;
1057   case '\n':
1058     OS << "'\\n'";
1059     break;
1060   case '\r':
1061     OS << "'\\r'";
1062     break;
1063   case '\t':
1064     OS << "'\\t'";
1065     break;
1066   case '\v':
1067     OS << "'\\v'";
1068     break;
1069   default:
1070     // A character literal might be sign-extended, which
1071     // would result in an invalid \U escape sequence.
1072     // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1073     // are not correctly handled.
1074     if ((value & ~0xFFu) == ~0xFFu && Node->getKind() == CharacterLiteral::Ascii)
1075       value &= 0xFFu;
1076     if (value < 256 && isPrintable((unsigned char)value))
1077       OS << "'" << (char)value << "'";
1078     else if (value < 256)
1079       OS << "'\\x" << llvm::format("%02x", value) << "'";
1080     else if (value <= 0xFFFF)
1081       OS << "'\\u" << llvm::format("%04x", value) << "'";
1082     else
1083       OS << "'\\U" << llvm::format("%08x", value) << "'";
1084   }
1085 }
1086 
1087 /// Prints the given expression using the original source text. Returns true on
1088 /// success, false otherwise.
1089 static bool printExprAsWritten(raw_ostream &OS, Expr *E,
1090                                const ASTContext *Context) {
1091   if (!Context)
1092     return false;
1093   bool Invalid = false;
1094   StringRef Source = Lexer::getSourceText(
1095       CharSourceRange::getTokenRange(E->getSourceRange()),
1096       Context->getSourceManager(), Context->getLangOpts(), &Invalid);
1097   if (!Invalid) {
1098     OS << Source;
1099     return true;
1100   }
1101   return false;
1102 }
1103 
1104 void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
1105   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1106     return;
1107   bool isSigned = Node->getType()->isSignedIntegerType();
1108   OS << Node->getValue().toString(10, isSigned);
1109 
1110   // Emit suffixes.  Integer literals are always a builtin integer type.
1111   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1112   default: llvm_unreachable("Unexpected type for integer literal!");
1113   case BuiltinType::Char_S:
1114   case BuiltinType::Char_U:    OS << "i8"; break;
1115   case BuiltinType::UChar:     OS << "Ui8"; break;
1116   case BuiltinType::Short:     OS << "i16"; break;
1117   case BuiltinType::UShort:    OS << "Ui16"; break;
1118   case BuiltinType::Int:       break; // no suffix.
1119   case BuiltinType::UInt:      OS << 'U'; break;
1120   case BuiltinType::Long:      OS << 'L'; break;
1121   case BuiltinType::ULong:     OS << "UL"; break;
1122   case BuiltinType::LongLong:  OS << "LL"; break;
1123   case BuiltinType::ULongLong: OS << "ULL"; break;
1124   }
1125 }
1126 
1127 void StmtPrinter::VisitFixedPointLiteral(FixedPointLiteral *Node) {
1128   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1129     return;
1130   OS << Node->getValueAsString(/*Radix=*/10);
1131 
1132   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1133     default: llvm_unreachable("Unexpected type for fixed point literal!");
1134     case BuiltinType::ShortFract:   OS << "hr"; break;
1135     case BuiltinType::ShortAccum:   OS << "hk"; break;
1136     case BuiltinType::UShortFract:  OS << "uhr"; break;
1137     case BuiltinType::UShortAccum:  OS << "uhk"; break;
1138     case BuiltinType::Fract:        OS << "r"; break;
1139     case BuiltinType::Accum:        OS << "k"; break;
1140     case BuiltinType::UFract:       OS << "ur"; break;
1141     case BuiltinType::UAccum:       OS << "uk"; break;
1142     case BuiltinType::LongFract:    OS << "lr"; break;
1143     case BuiltinType::LongAccum:    OS << "lk"; break;
1144     case BuiltinType::ULongFract:   OS << "ulr"; break;
1145     case BuiltinType::ULongAccum:   OS << "ulk"; break;
1146   }
1147 }
1148 
1149 static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
1150                                  bool PrintSuffix) {
1151   SmallString<16> Str;
1152   Node->getValue().toString(Str);
1153   OS << Str;
1154   if (Str.find_first_not_of("-0123456789") == StringRef::npos)
1155     OS << '.'; // Trailing dot in order to separate from ints.
1156 
1157   if (!PrintSuffix)
1158     return;
1159 
1160   // Emit suffixes.  Float literals are always a builtin float type.
1161   switch (Node->getType()->castAs<BuiltinType>()->getKind()) {
1162   default: llvm_unreachable("Unexpected type for float literal!");
1163   case BuiltinType::Half:       break; // FIXME: suffix?
1164   case BuiltinType::Double:     break; // no suffix.
1165   case BuiltinType::Float16:    OS << "F16"; break;
1166   case BuiltinType::Float:      OS << 'F'; break;
1167   case BuiltinType::LongDouble: OS << 'L'; break;
1168   case BuiltinType::Float128:   OS << 'Q'; break;
1169   }
1170 }
1171 
1172 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
1173   if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1174     return;
1175   PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
1176 }
1177 
1178 void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
1179   PrintExpr(Node->getSubExpr());
1180   OS << "i";
1181 }
1182 
1183 void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
1184   Str->outputString(OS);
1185 }
1186 
1187 void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
1188   OS << "(";
1189   PrintExpr(Node->getSubExpr());
1190   OS << ")";
1191 }
1192 
1193 void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
1194   if (!Node->isPostfix()) {
1195     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1196 
1197     // Print a space if this is an "identifier operator" like __real, or if
1198     // it might be concatenated incorrectly like '+'.
1199     switch (Node->getOpcode()) {
1200     default: break;
1201     case UO_Real:
1202     case UO_Imag:
1203     case UO_Extension:
1204       OS << ' ';
1205       break;
1206     case UO_Plus:
1207     case UO_Minus:
1208       if (isa<UnaryOperator>(Node->getSubExpr()))
1209         OS << ' ';
1210       break;
1211     }
1212   }
1213   PrintExpr(Node->getSubExpr());
1214 
1215   if (Node->isPostfix())
1216     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1217 }
1218 
1219 void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
1220   OS << "__builtin_offsetof(";
1221   Node->getTypeSourceInfo()->getType().print(OS, Policy);
1222   OS << ", ";
1223   bool PrintedSomething = false;
1224   for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
1225     OffsetOfNode ON = Node->getComponent(i);
1226     if (ON.getKind() == OffsetOfNode::Array) {
1227       // Array node
1228       OS << "[";
1229       PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
1230       OS << "]";
1231       PrintedSomething = true;
1232       continue;
1233     }
1234 
1235     // Skip implicit base indirections.
1236     if (ON.getKind() == OffsetOfNode::Base)
1237       continue;
1238 
1239     // Field or identifier node.
1240     IdentifierInfo *Id = ON.getFieldName();
1241     if (!Id)
1242       continue;
1243 
1244     if (PrintedSomething)
1245       OS << ".";
1246     else
1247       PrintedSomething = true;
1248     OS << Id->getName();
1249   }
1250   OS << ")";
1251 }
1252 
1253 void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
1254   switch(Node->getKind()) {
1255   case UETT_SizeOf:
1256     OS << "sizeof";
1257     break;
1258   case UETT_AlignOf:
1259     if (Policy.Alignof)
1260       OS << "alignof";
1261     else if (Policy.UnderscoreAlignof)
1262       OS << "_Alignof";
1263     else
1264       OS << "__alignof";
1265     break;
1266   case UETT_PreferredAlignOf:
1267     OS << "__alignof";
1268     break;
1269   case UETT_VecStep:
1270     OS << "vec_step";
1271     break;
1272   case UETT_OpenMPRequiredSimdAlign:
1273     OS << "__builtin_omp_required_simd_align";
1274     break;
1275   }
1276   if (Node->isArgumentType()) {
1277     OS << '(';
1278     Node->getArgumentType().print(OS, Policy);
1279     OS << ')';
1280   } else {
1281     OS << " ";
1282     PrintExpr(Node->getArgumentExpr());
1283   }
1284 }
1285 
1286 void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
1287   OS << "_Generic(";
1288   PrintExpr(Node->getControllingExpr());
1289   for (const GenericSelectionExpr::Association &Assoc : Node->associations()) {
1290     OS << ", ";
1291     QualType T = Assoc.getType();
1292     if (T.isNull())
1293       OS << "default";
1294     else
1295       T.print(OS, Policy);
1296     OS << ": ";
1297     PrintExpr(Assoc.getAssociationExpr());
1298   }
1299   OS << ")";
1300 }
1301 
1302 void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
1303   PrintExpr(Node->getLHS());
1304   OS << "[";
1305   PrintExpr(Node->getRHS());
1306   OS << "]";
1307 }
1308 
1309 void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) {
1310   PrintExpr(Node->getBase());
1311   OS << "[";
1312   if (Node->getLowerBound())
1313     PrintExpr(Node->getLowerBound());
1314   if (Node->getColonLoc().isValid()) {
1315     OS << ":";
1316     if (Node->getLength())
1317       PrintExpr(Node->getLength());
1318   }
1319   OS << "]";
1320 }
1321 
1322 void StmtPrinter::PrintCallArgs(CallExpr *Call) {
1323   for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
1324     if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
1325       // Don't print any defaulted arguments
1326       break;
1327     }
1328 
1329     if (i) OS << ", ";
1330     PrintExpr(Call->getArg(i));
1331   }
1332 }
1333 
1334 void StmtPrinter::VisitCallExpr(CallExpr *Call) {
1335   PrintExpr(Call->getCallee());
1336   OS << "(";
1337   PrintCallArgs(Call);
1338   OS << ")";
1339 }
1340 
1341 static bool isImplicitThis(const Expr *E) {
1342   if (const auto *TE = dyn_cast<CXXThisExpr>(E))
1343     return TE->isImplicit();
1344   return false;
1345 }
1346 
1347 void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
1348   if (!Policy.SuppressImplicitBase || !isImplicitThis(Node->getBase())) {
1349     PrintExpr(Node->getBase());
1350 
1351     auto *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
1352     FieldDecl *ParentDecl =
1353         ParentMember ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl())
1354                      : nullptr;
1355 
1356     if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
1357       OS << (Node->isArrow() ? "->" : ".");
1358   }
1359 
1360   if (auto *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
1361     if (FD->isAnonymousStructOrUnion())
1362       return;
1363 
1364   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1365     Qualifier->print(OS, Policy);
1366   if (Node->hasTemplateKeyword())
1367     OS << "template ";
1368   OS << Node->getMemberNameInfo();
1369   if (Node->hasExplicitTemplateArgs())
1370     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
1371 }
1372 
1373 void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
1374   PrintExpr(Node->getBase());
1375   OS << (Node->isArrow() ? "->isa" : ".isa");
1376 }
1377 
1378 void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
1379   PrintExpr(Node->getBase());
1380   OS << ".";
1381   OS << Node->getAccessor().getName();
1382 }
1383 
1384 void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
1385   OS << '(';
1386   Node->getTypeAsWritten().print(OS, Policy);
1387   OS << ')';
1388   PrintExpr(Node->getSubExpr());
1389 }
1390 
1391 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
1392   OS << '(';
1393   Node->getType().print(OS, Policy);
1394   OS << ')';
1395   PrintExpr(Node->getInitializer());
1396 }
1397 
1398 void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
1399   // No need to print anything, simply forward to the subexpression.
1400   PrintExpr(Node->getSubExpr());
1401 }
1402 
1403 void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
1404   PrintExpr(Node->getLHS());
1405   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1406   PrintExpr(Node->getRHS());
1407 }
1408 
1409 void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
1410   PrintExpr(Node->getLHS());
1411   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1412   PrintExpr(Node->getRHS());
1413 }
1414 
1415 void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
1416   PrintExpr(Node->getCond());
1417   OS << " ? ";
1418   PrintExpr(Node->getLHS());
1419   OS << " : ";
1420   PrintExpr(Node->getRHS());
1421 }
1422 
1423 // GNU extensions.
1424 
1425 void
1426 StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
1427   PrintExpr(Node->getCommon());
1428   OS << " ?: ";
1429   PrintExpr(Node->getFalseExpr());
1430 }
1431 
1432 void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
1433   OS << "&&" << Node->getLabel()->getName();
1434 }
1435 
1436 void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
1437   OS << "(";
1438   PrintRawCompoundStmt(E->getSubStmt());
1439   OS << ")";
1440 }
1441 
1442 void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
1443   OS << "__builtin_choose_expr(";
1444   PrintExpr(Node->getCond());
1445   OS << ", ";
1446   PrintExpr(Node->getLHS());
1447   OS << ", ";
1448   PrintExpr(Node->getRHS());
1449   OS << ")";
1450 }
1451 
1452 void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1453   OS << "__null";
1454 }
1455 
1456 void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1457   OS << "__builtin_shufflevector(";
1458   for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
1459     if (i) OS << ", ";
1460     PrintExpr(Node->getExpr(i));
1461   }
1462   OS << ")";
1463 }
1464 
1465 void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) {
1466   OS << "__builtin_convertvector(";
1467   PrintExpr(Node->getSrcExpr());
1468   OS << ", ";
1469   Node->getType().print(OS, Policy);
1470   OS << ")";
1471 }
1472 
1473 void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1474   if (Node->getSyntacticForm()) {
1475     Visit(Node->getSyntacticForm());
1476     return;
1477   }
1478 
1479   OS << "{";
1480   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1481     if (i) OS << ", ";
1482     if (Node->getInit(i))
1483       PrintExpr(Node->getInit(i));
1484     else
1485       OS << "{}";
1486   }
1487   OS << "}";
1488 }
1489 
1490 void StmtPrinter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *Node) {
1491   // There's no way to express this expression in any of our supported
1492   // languages, so just emit something terse and (hopefully) clear.
1493   OS << "{";
1494   PrintExpr(Node->getSubExpr());
1495   OS << "}";
1496 }
1497 
1498 void StmtPrinter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *Node) {
1499   OS << "*";
1500 }
1501 
1502 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1503   OS << "(";
1504   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1505     if (i) OS << ", ";
1506     PrintExpr(Node->getExpr(i));
1507   }
1508   OS << ")";
1509 }
1510 
1511 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1512   bool NeedsEquals = true;
1513   for (const DesignatedInitExpr::Designator &D : Node->designators()) {
1514     if (D.isFieldDesignator()) {
1515       if (D.getDotLoc().isInvalid()) {
1516         if (IdentifierInfo *II = D.getFieldName()) {
1517           OS << II->getName() << ":";
1518           NeedsEquals = false;
1519         }
1520       } else {
1521         OS << "." << D.getFieldName()->getName();
1522       }
1523     } else {
1524       OS << "[";
1525       if (D.isArrayDesignator()) {
1526         PrintExpr(Node->getArrayIndex(D));
1527       } else {
1528         PrintExpr(Node->getArrayRangeStart(D));
1529         OS << " ... ";
1530         PrintExpr(Node->getArrayRangeEnd(D));
1531       }
1532       OS << "]";
1533     }
1534   }
1535 
1536   if (NeedsEquals)
1537     OS << " = ";
1538   else
1539     OS << " ";
1540   PrintExpr(Node->getInit());
1541 }
1542 
1543 void StmtPrinter::VisitDesignatedInitUpdateExpr(
1544     DesignatedInitUpdateExpr *Node) {
1545   OS << "{";
1546   OS << "/*base*/";
1547   PrintExpr(Node->getBase());
1548   OS << ", ";
1549 
1550   OS << "/*updater*/";
1551   PrintExpr(Node->getUpdater());
1552   OS << "}";
1553 }
1554 
1555 void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) {
1556   OS << "/*no init*/";
1557 }
1558 
1559 void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1560   if (Node->getType()->getAsCXXRecordDecl()) {
1561     OS << "/*implicit*/";
1562     Node->getType().print(OS, Policy);
1563     OS << "()";
1564   } else {
1565     OS << "/*implicit*/(";
1566     Node->getType().print(OS, Policy);
1567     OS << ')';
1568     if (Node->getType()->isRecordType())
1569       OS << "{}";
1570     else
1571       OS << 0;
1572   }
1573 }
1574 
1575 void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1576   OS << "__builtin_va_arg(";
1577   PrintExpr(Node->getSubExpr());
1578   OS << ", ";
1579   Node->getType().print(OS, Policy);
1580   OS << ")";
1581 }
1582 
1583 void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1584   PrintExpr(Node->getSyntacticForm());
1585 }
1586 
1587 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1588   const char *Name = nullptr;
1589   switch (Node->getOp()) {
1590 #define BUILTIN(ID, TYPE, ATTRS)
1591 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1592   case AtomicExpr::AO ## ID: \
1593     Name = #ID "("; \
1594     break;
1595 #include "clang/Basic/Builtins.def"
1596   }
1597   OS << Name;
1598 
1599   // AtomicExpr stores its subexpressions in a permuted order.
1600   PrintExpr(Node->getPtr());
1601   if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1602       Node->getOp() != AtomicExpr::AO__atomic_load_n &&
1603       Node->getOp() != AtomicExpr::AO__opencl_atomic_load) {
1604     OS << ", ";
1605     PrintExpr(Node->getVal1());
1606   }
1607   if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1608       Node->isCmpXChg()) {
1609     OS << ", ";
1610     PrintExpr(Node->getVal2());
1611   }
1612   if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1613       Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1614     OS << ", ";
1615     PrintExpr(Node->getWeak());
1616   }
1617   if (Node->getOp() != AtomicExpr::AO__c11_atomic_init &&
1618       Node->getOp() != AtomicExpr::AO__opencl_atomic_init) {
1619     OS << ", ";
1620     PrintExpr(Node->getOrder());
1621   }
1622   if (Node->isCmpXChg()) {
1623     OS << ", ";
1624     PrintExpr(Node->getOrderFail());
1625   }
1626   OS << ")";
1627 }
1628 
1629 // C++
1630 void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1631   OverloadedOperatorKind Kind = Node->getOperator();
1632   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1633     if (Node->getNumArgs() == 1) {
1634       OS << getOperatorSpelling(Kind) << ' ';
1635       PrintExpr(Node->getArg(0));
1636     } else {
1637       PrintExpr(Node->getArg(0));
1638       OS << ' ' << getOperatorSpelling(Kind);
1639     }
1640   } else if (Kind == OO_Arrow) {
1641     PrintExpr(Node->getArg(0));
1642   } else if (Kind == OO_Call) {
1643     PrintExpr(Node->getArg(0));
1644     OS << '(';
1645     for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1646       if (ArgIdx > 1)
1647         OS << ", ";
1648       if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1649         PrintExpr(Node->getArg(ArgIdx));
1650     }
1651     OS << ')';
1652   } else if (Kind == OO_Subscript) {
1653     PrintExpr(Node->getArg(0));
1654     OS << '[';
1655     PrintExpr(Node->getArg(1));
1656     OS << ']';
1657   } else if (Node->getNumArgs() == 1) {
1658     OS << getOperatorSpelling(Kind) << ' ';
1659     PrintExpr(Node->getArg(0));
1660   } else if (Node->getNumArgs() == 2) {
1661     PrintExpr(Node->getArg(0));
1662     OS << ' ' << getOperatorSpelling(Kind) << ' ';
1663     PrintExpr(Node->getArg(1));
1664   } else {
1665     llvm_unreachable("unknown overloaded operator");
1666   }
1667 }
1668 
1669 void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1670   // If we have a conversion operator call only print the argument.
1671   CXXMethodDecl *MD = Node->getMethodDecl();
1672   if (MD && isa<CXXConversionDecl>(MD)) {
1673     PrintExpr(Node->getImplicitObjectArgument());
1674     return;
1675   }
1676   VisitCallExpr(cast<CallExpr>(Node));
1677 }
1678 
1679 void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1680   PrintExpr(Node->getCallee());
1681   OS << "<<<";
1682   PrintCallArgs(Node->getConfig());
1683   OS << ">>>(";
1684   PrintCallArgs(Node);
1685   OS << ")";
1686 }
1687 
1688 void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1689   OS << Node->getCastName() << '<';
1690   Node->getTypeAsWritten().print(OS, Policy);
1691   OS << ">(";
1692   PrintExpr(Node->getSubExpr());
1693   OS << ")";
1694 }
1695 
1696 void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1697   VisitCXXNamedCastExpr(Node);
1698 }
1699 
1700 void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1701   VisitCXXNamedCastExpr(Node);
1702 }
1703 
1704 void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1705   VisitCXXNamedCastExpr(Node);
1706 }
1707 
1708 void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1709   VisitCXXNamedCastExpr(Node);
1710 }
1711 
1712 void StmtPrinter::VisitBuiltinBitCastExpr(BuiltinBitCastExpr *Node) {
1713   OS << "__builtin_bit_cast(";
1714   Node->getTypeInfoAsWritten()->getType().print(OS, Policy);
1715   OS << ", ";
1716   PrintExpr(Node->getSubExpr());
1717   OS << ")";
1718 }
1719 
1720 void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1721   OS << "typeid(";
1722   if (Node->isTypeOperand()) {
1723     Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1724   } else {
1725     PrintExpr(Node->getExprOperand());
1726   }
1727   OS << ")";
1728 }
1729 
1730 void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1731   OS << "__uuidof(";
1732   if (Node->isTypeOperand()) {
1733     Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1734   } else {
1735     PrintExpr(Node->getExprOperand());
1736   }
1737   OS << ")";
1738 }
1739 
1740 void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
1741   PrintExpr(Node->getBaseExpr());
1742   if (Node->isArrow())
1743     OS << "->";
1744   else
1745     OS << ".";
1746   if (NestedNameSpecifier *Qualifier =
1747       Node->getQualifierLoc().getNestedNameSpecifier())
1748     Qualifier->print(OS, Policy);
1749   OS << Node->getPropertyDecl()->getDeclName();
1750 }
1751 
1752 void StmtPrinter::VisitMSPropertySubscriptExpr(MSPropertySubscriptExpr *Node) {
1753   PrintExpr(Node->getBase());
1754   OS << "[";
1755   PrintExpr(Node->getIdx());
1756   OS << "]";
1757 }
1758 
1759 void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1760   switch (Node->getLiteralOperatorKind()) {
1761   case UserDefinedLiteral::LOK_Raw:
1762     OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1763     break;
1764   case UserDefinedLiteral::LOK_Template: {
1765     const auto *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1766     const TemplateArgumentList *Args =
1767       cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1768     assert(Args);
1769 
1770     if (Args->size() != 1) {
1771       OS << "operator\"\"" << Node->getUDSuffix()->getName();
1772       printTemplateArgumentList(OS, Args->asArray(), Policy);
1773       OS << "()";
1774       return;
1775     }
1776 
1777     const TemplateArgument &Pack = Args->get(0);
1778     for (const auto &P : Pack.pack_elements()) {
1779       char C = (char)P.getAsIntegral().getZExtValue();
1780       OS << C;
1781     }
1782     break;
1783   }
1784   case UserDefinedLiteral::LOK_Integer: {
1785     // Print integer literal without suffix.
1786     const auto *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1787     OS << Int->getValue().toString(10, /*isSigned*/false);
1788     break;
1789   }
1790   case UserDefinedLiteral::LOK_Floating: {
1791     // Print floating literal without suffix.
1792     auto *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1793     PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1794     break;
1795   }
1796   case UserDefinedLiteral::LOK_String:
1797   case UserDefinedLiteral::LOK_Character:
1798     PrintExpr(Node->getCookedLiteral());
1799     break;
1800   }
1801   OS << Node->getUDSuffix()->getName();
1802 }
1803 
1804 void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1805   OS << (Node->getValue() ? "true" : "false");
1806 }
1807 
1808 void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1809   OS << "nullptr";
1810 }
1811 
1812 void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1813   OS << "this";
1814 }
1815 
1816 void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1817   if (!Node->getSubExpr())
1818     OS << "throw";
1819   else {
1820     OS << "throw ";
1821     PrintExpr(Node->getSubExpr());
1822   }
1823 }
1824 
1825 void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1826   // Nothing to print: we picked up the default argument.
1827 }
1828 
1829 void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
1830   // Nothing to print: we picked up the default initializer.
1831 }
1832 
1833 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1834   Node->getType().print(OS, Policy);
1835   // If there are no parens, this is list-initialization, and the braces are
1836   // part of the syntax of the inner construct.
1837   if (Node->getLParenLoc().isValid())
1838     OS << "(";
1839   PrintExpr(Node->getSubExpr());
1840   if (Node->getLParenLoc().isValid())
1841     OS << ")";
1842 }
1843 
1844 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1845   PrintExpr(Node->getSubExpr());
1846 }
1847 
1848 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1849   Node->getType().print(OS, Policy);
1850   if (Node->isStdInitListInitialization())
1851     /* Nothing to do; braces are part of creating the std::initializer_list. */;
1852   else if (Node->isListInitialization())
1853     OS << "{";
1854   else
1855     OS << "(";
1856   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1857                                          ArgEnd = Node->arg_end();
1858        Arg != ArgEnd; ++Arg) {
1859     if ((*Arg)->isDefaultArgument())
1860       break;
1861     if (Arg != Node->arg_begin())
1862       OS << ", ";
1863     PrintExpr(*Arg);
1864   }
1865   if (Node->isStdInitListInitialization())
1866     /* See above. */;
1867   else if (Node->isListInitialization())
1868     OS << "}";
1869   else
1870     OS << ")";
1871 }
1872 
1873 void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1874   OS << '[';
1875   bool NeedComma = false;
1876   switch (Node->getCaptureDefault()) {
1877   case LCD_None:
1878     break;
1879 
1880   case LCD_ByCopy:
1881     OS << '=';
1882     NeedComma = true;
1883     break;
1884 
1885   case LCD_ByRef:
1886     OS << '&';
1887     NeedComma = true;
1888     break;
1889   }
1890   for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1891                                  CEnd = Node->explicit_capture_end();
1892        C != CEnd;
1893        ++C) {
1894     if (C->capturesVLAType())
1895       continue;
1896 
1897     if (NeedComma)
1898       OS << ", ";
1899     NeedComma = true;
1900 
1901     switch (C->getCaptureKind()) {
1902     case LCK_This:
1903       OS << "this";
1904       break;
1905 
1906     case LCK_StarThis:
1907       OS << "*this";
1908       break;
1909 
1910     case LCK_ByRef:
1911       if (Node->getCaptureDefault() != LCD_ByRef || Node->isInitCapture(C))
1912         OS << '&';
1913       OS << C->getCapturedVar()->getName();
1914       break;
1915 
1916     case LCK_ByCopy:
1917       OS << C->getCapturedVar()->getName();
1918       break;
1919 
1920     case LCK_VLAType:
1921       llvm_unreachable("VLA type in explicit captures.");
1922     }
1923 
1924     if (C->isPackExpansion())
1925       OS << "...";
1926 
1927     if (Node->isInitCapture(C))
1928       PrintExpr(C->getCapturedVar()->getInit());
1929   }
1930   OS << ']';
1931 
1932   if (!Node->getExplicitTemplateParameters().empty()) {
1933     Node->getTemplateParameterList()->print(
1934         OS, Node->getLambdaClass()->getASTContext(),
1935         /*OmitTemplateKW*/true);
1936   }
1937 
1938   if (Node->hasExplicitParameters()) {
1939     OS << '(';
1940     CXXMethodDecl *Method = Node->getCallOperator();
1941     NeedComma = false;
1942     for (const auto *P : Method->parameters()) {
1943       if (NeedComma) {
1944         OS << ", ";
1945       } else {
1946         NeedComma = true;
1947       }
1948       std::string ParamStr = P->getNameAsString();
1949       P->getOriginalType().print(OS, Policy, ParamStr);
1950     }
1951     if (Method->isVariadic()) {
1952       if (NeedComma)
1953         OS << ", ";
1954       OS << "...";
1955     }
1956     OS << ')';
1957 
1958     if (Node->isMutable())
1959       OS << " mutable";
1960 
1961     auto *Proto = Method->getType()->castAs<FunctionProtoType>();
1962     Proto->printExceptionSpecification(OS, Policy);
1963 
1964     // FIXME: Attributes
1965 
1966     // Print the trailing return type if it was specified in the source.
1967     if (Node->hasExplicitResultType()) {
1968       OS << " -> ";
1969       Proto->getReturnType().print(OS, Policy);
1970     }
1971   }
1972 
1973   // Print the body.
1974   OS << ' ';
1975   if (Policy.TerseOutput)
1976     OS << "{}";
1977   else
1978     PrintRawCompoundStmt(Node->getBody());
1979 }
1980 
1981 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1982   if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1983     TSInfo->getType().print(OS, Policy);
1984   else
1985     Node->getType().print(OS, Policy);
1986   OS << "()";
1987 }
1988 
1989 void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1990   if (E->isGlobalNew())
1991     OS << "::";
1992   OS << "new ";
1993   unsigned NumPlace = E->getNumPlacementArgs();
1994   if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
1995     OS << "(";
1996     PrintExpr(E->getPlacementArg(0));
1997     for (unsigned i = 1; i < NumPlace; ++i) {
1998       if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
1999         break;
2000       OS << ", ";
2001       PrintExpr(E->getPlacementArg(i));
2002     }
2003     OS << ") ";
2004   }
2005   if (E->isParenTypeId())
2006     OS << "(";
2007   std::string TypeS;
2008   if (Optional<Expr *> Size = E->getArraySize()) {
2009     llvm::raw_string_ostream s(TypeS);
2010     s << '[';
2011     if (*Size)
2012       (*Size)->printPretty(s, Helper, Policy);
2013     s << ']';
2014   }
2015   E->getAllocatedType().print(OS, Policy, TypeS);
2016   if (E->isParenTypeId())
2017     OS << ")";
2018 
2019   CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
2020   if (InitStyle) {
2021     if (InitStyle == CXXNewExpr::CallInit)
2022       OS << "(";
2023     PrintExpr(E->getInitializer());
2024     if (InitStyle == CXXNewExpr::CallInit)
2025       OS << ")";
2026   }
2027 }
2028 
2029 void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2030   if (E->isGlobalDelete())
2031     OS << "::";
2032   OS << "delete ";
2033   if (E->isArrayForm())
2034     OS << "[] ";
2035   PrintExpr(E->getArgument());
2036 }
2037 
2038 void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
2039   PrintExpr(E->getBase());
2040   if (E->isArrow())
2041     OS << "->";
2042   else
2043     OS << '.';
2044   if (E->getQualifier())
2045     E->getQualifier()->print(OS, Policy);
2046   OS << "~";
2047 
2048   if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
2049     OS << II->getName();
2050   else
2051     E->getDestroyedType().print(OS, Policy);
2052 }
2053 
2054 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
2055   if (E->isListInitialization() && !E->isStdInitListInitialization())
2056     OS << "{";
2057 
2058   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
2059     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
2060       // Don't print any defaulted arguments
2061       break;
2062     }
2063 
2064     if (i) OS << ", ";
2065     PrintExpr(E->getArg(i));
2066   }
2067 
2068   if (E->isListInitialization() && !E->isStdInitListInitialization())
2069     OS << "}";
2070 }
2071 
2072 void StmtPrinter::VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E) {
2073   // Parens are printed by the surrounding context.
2074   OS << "<forwarded>";
2075 }
2076 
2077 void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
2078   PrintExpr(E->getSubExpr());
2079 }
2080 
2081 void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
2082   // Just forward to the subexpression.
2083   PrintExpr(E->getSubExpr());
2084 }
2085 
2086 void
2087 StmtPrinter::VisitCXXUnresolvedConstructExpr(
2088                                            CXXUnresolvedConstructExpr *Node) {
2089   Node->getTypeAsWritten().print(OS, Policy);
2090   OS << "(";
2091   for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
2092                                              ArgEnd = Node->arg_end();
2093        Arg != ArgEnd; ++Arg) {
2094     if (Arg != Node->arg_begin())
2095       OS << ", ";
2096     PrintExpr(*Arg);
2097   }
2098   OS << ")";
2099 }
2100 
2101 void StmtPrinter::VisitCXXDependentScopeMemberExpr(
2102                                          CXXDependentScopeMemberExpr *Node) {
2103   if (!Node->isImplicitAccess()) {
2104     PrintExpr(Node->getBase());
2105     OS << (Node->isArrow() ? "->" : ".");
2106   }
2107   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2108     Qualifier->print(OS, Policy);
2109   if (Node->hasTemplateKeyword())
2110     OS << "template ";
2111   OS << Node->getMemberNameInfo();
2112   if (Node->hasExplicitTemplateArgs())
2113     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2114 }
2115 
2116 void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
2117   if (!Node->isImplicitAccess()) {
2118     PrintExpr(Node->getBase());
2119     OS << (Node->isArrow() ? "->" : ".");
2120   }
2121   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2122     Qualifier->print(OS, Policy);
2123   if (Node->hasTemplateKeyword())
2124     OS << "template ";
2125   OS << Node->getMemberNameInfo();
2126   if (Node->hasExplicitTemplateArgs())
2127     printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2128 }
2129 
2130 static const char *getTypeTraitName(TypeTrait TT) {
2131   switch (TT) {
2132 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2133 case clang::UTT_##Name: return #Spelling;
2134 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2135 case clang::BTT_##Name: return #Spelling;
2136 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2137   case clang::TT_##Name: return #Spelling;
2138 #include "clang/Basic/TokenKinds.def"
2139   }
2140   llvm_unreachable("Type trait not covered by switch");
2141 }
2142 
2143 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
2144   switch (ATT) {
2145   case ATT_ArrayRank:        return "__array_rank";
2146   case ATT_ArrayExtent:      return "__array_extent";
2147   }
2148   llvm_unreachable("Array type trait not covered by switch");
2149 }
2150 
2151 static const char *getExpressionTraitName(ExpressionTrait ET) {
2152   switch (ET) {
2153   case ET_IsLValueExpr:      return "__is_lvalue_expr";
2154   case ET_IsRValueExpr:      return "__is_rvalue_expr";
2155   }
2156   llvm_unreachable("Expression type trait not covered by switch");
2157 }
2158 
2159 void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
2160   OS << getTypeTraitName(E->getTrait()) << "(";
2161   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
2162     if (I > 0)
2163       OS << ", ";
2164     E->getArg(I)->getType().print(OS, Policy);
2165   }
2166   OS << ")";
2167 }
2168 
2169 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2170   OS << getTypeTraitName(E->getTrait()) << '(';
2171   E->getQueriedType().print(OS, Policy);
2172   OS << ')';
2173 }
2174 
2175 void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2176   OS << getExpressionTraitName(E->getTrait()) << '(';
2177   PrintExpr(E->getQueriedExpression());
2178   OS << ')';
2179 }
2180 
2181 void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
2182   OS << "noexcept(";
2183   PrintExpr(E->getOperand());
2184   OS << ")";
2185 }
2186 
2187 void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
2188   PrintExpr(E->getPattern());
2189   OS << "...";
2190 }
2191 
2192 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2193   OS << "sizeof...(" << *E->getPack() << ")";
2194 }
2195 
2196 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
2197                                        SubstNonTypeTemplateParmPackExpr *Node) {
2198   OS << *Node->getParameterPack();
2199 }
2200 
2201 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
2202                                        SubstNonTypeTemplateParmExpr *Node) {
2203   Visit(Node->getReplacement());
2204 }
2205 
2206 void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
2207   OS << *E->getParameterPack();
2208 }
2209 
2210 void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
2211   PrintExpr(Node->GetTemporaryExpr());
2212 }
2213 
2214 void StmtPrinter::VisitCXXFoldExpr(CXXFoldExpr *E) {
2215   OS << "(";
2216   if (E->getLHS()) {
2217     PrintExpr(E->getLHS());
2218     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2219   }
2220   OS << "...";
2221   if (E->getRHS()) {
2222     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2223     PrintExpr(E->getRHS());
2224   }
2225   OS << ")";
2226 }
2227 
2228 // C++ Coroutines TS
2229 
2230 void StmtPrinter::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) {
2231   Visit(S->getBody());
2232 }
2233 
2234 void StmtPrinter::VisitCoreturnStmt(CoreturnStmt *S) {
2235   OS << "co_return";
2236   if (S->getOperand()) {
2237     OS << " ";
2238     Visit(S->getOperand());
2239   }
2240   OS << ";";
2241 }
2242 
2243 void StmtPrinter::VisitCoawaitExpr(CoawaitExpr *S) {
2244   OS << "co_await ";
2245   PrintExpr(S->getOperand());
2246 }
2247 
2248 void StmtPrinter::VisitDependentCoawaitExpr(DependentCoawaitExpr *S) {
2249   OS << "co_await ";
2250   PrintExpr(S->getOperand());
2251 }
2252 
2253 void StmtPrinter::VisitCoyieldExpr(CoyieldExpr *S) {
2254   OS << "co_yield ";
2255   PrintExpr(S->getOperand());
2256 }
2257 
2258 // Obj-C
2259 
2260 void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
2261   OS << "@";
2262   VisitStringLiteral(Node->getString());
2263 }
2264 
2265 void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
2266   OS << "@";
2267   Visit(E->getSubExpr());
2268 }
2269 
2270 void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
2271   OS << "@[ ";
2272   ObjCArrayLiteral::child_range Ch = E->children();
2273   for (auto I = Ch.begin(), E = Ch.end(); I != E; ++I) {
2274     if (I != Ch.begin())
2275       OS << ", ";
2276     Visit(*I);
2277   }
2278   OS << " ]";
2279 }
2280 
2281 void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
2282   OS << "@{ ";
2283   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
2284     if (I > 0)
2285       OS << ", ";
2286 
2287     ObjCDictionaryElement Element = E->getKeyValueElement(I);
2288     Visit(Element.Key);
2289     OS << " : ";
2290     Visit(Element.Value);
2291     if (Element.isPackExpansion())
2292       OS << "...";
2293   }
2294   OS << " }";
2295 }
2296 
2297 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
2298   OS << "@encode(";
2299   Node->getEncodedType().print(OS, Policy);
2300   OS << ')';
2301 }
2302 
2303 void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
2304   OS << "@selector(";
2305   Node->getSelector().print(OS);
2306   OS << ')';
2307 }
2308 
2309 void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
2310   OS << "@protocol(" << *Node->getProtocol() << ')';
2311 }
2312 
2313 void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
2314   OS << "[";
2315   switch (Mess->getReceiverKind()) {
2316   case ObjCMessageExpr::Instance:
2317     PrintExpr(Mess->getInstanceReceiver());
2318     break;
2319 
2320   case ObjCMessageExpr::Class:
2321     Mess->getClassReceiver().print(OS, Policy);
2322     break;
2323 
2324   case ObjCMessageExpr::SuperInstance:
2325   case ObjCMessageExpr::SuperClass:
2326     OS << "Super";
2327     break;
2328   }
2329 
2330   OS << ' ';
2331   Selector selector = Mess->getSelector();
2332   if (selector.isUnarySelector()) {
2333     OS << selector.getNameForSlot(0);
2334   } else {
2335     for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
2336       if (i < selector.getNumArgs()) {
2337         if (i > 0) OS << ' ';
2338         if (selector.getIdentifierInfoForSlot(i))
2339           OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
2340         else
2341            OS << ":";
2342       }
2343       else OS << ", "; // Handle variadic methods.
2344 
2345       PrintExpr(Mess->getArg(i));
2346     }
2347   }
2348   OS << "]";
2349 }
2350 
2351 void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
2352   OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
2353 }
2354 
2355 void
2356 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
2357   PrintExpr(E->getSubExpr());
2358 }
2359 
2360 void
2361 StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
2362   OS << '(' << E->getBridgeKindName();
2363   E->getType().print(OS, Policy);
2364   OS << ')';
2365   PrintExpr(E->getSubExpr());
2366 }
2367 
2368 void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
2369   BlockDecl *BD = Node->getBlockDecl();
2370   OS << "^";
2371 
2372   const FunctionType *AFT = Node->getFunctionType();
2373 
2374   if (isa<FunctionNoProtoType>(AFT)) {
2375     OS << "()";
2376   } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
2377     OS << '(';
2378     for (BlockDecl::param_iterator AI = BD->param_begin(),
2379          E = BD->param_end(); AI != E; ++AI) {
2380       if (AI != BD->param_begin()) OS << ", ";
2381       std::string ParamStr = (*AI)->getNameAsString();
2382       (*AI)->getType().print(OS, Policy, ParamStr);
2383     }
2384 
2385     const auto *FT = cast<FunctionProtoType>(AFT);
2386     if (FT->isVariadic()) {
2387       if (!BD->param_empty()) OS << ", ";
2388       OS << "...";
2389     }
2390     OS << ')';
2391   }
2392   OS << "{ }";
2393 }
2394 
2395 void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
2396   PrintExpr(Node->getSourceExpr());
2397 }
2398 
2399 void StmtPrinter::VisitTypoExpr(TypoExpr *Node) {
2400   // TODO: Print something reasonable for a TypoExpr, if necessary.
2401   llvm_unreachable("Cannot print TypoExpr nodes");
2402 }
2403 
2404 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
2405   OS << "__builtin_astype(";
2406   PrintExpr(Node->getSrcExpr());
2407   OS << ", ";
2408   Node->getType().print(OS, Policy);
2409   OS << ")";
2410 }
2411 
2412 //===----------------------------------------------------------------------===//
2413 // Stmt method implementations
2414 //===----------------------------------------------------------------------===//
2415 
2416 void Stmt::dumpPretty(const ASTContext &Context) const {
2417   printPretty(llvm::errs(), nullptr, PrintingPolicy(Context.getLangOpts()));
2418 }
2419 
2420 void Stmt::printPretty(raw_ostream &Out, PrinterHelper *Helper,
2421                        const PrintingPolicy &Policy, unsigned Indentation,
2422                        StringRef NL, const ASTContext *Context) const {
2423   StmtPrinter P(Out, Helper, Policy, Indentation, NL, Context);
2424   P.Visit(const_cast<Stmt *>(this));
2425 }
2426 
2427 void Stmt::printJson(raw_ostream &Out, PrinterHelper *Helper,
2428                      const PrintingPolicy &Policy, bool AddQuotes) const {
2429   std::string Buf;
2430   llvm::raw_string_ostream TempOut(Buf);
2431 
2432   printPretty(TempOut, Helper, Policy);
2433 
2434   Out << JsonFormat(TempOut.str(), AddQuotes);
2435 }
2436 
2437 //===----------------------------------------------------------------------===//
2438 // PrinterHelper
2439 //===----------------------------------------------------------------------===//
2440 
2441 // Implement virtual destructor.
2442 PrinterHelper::~PrinterHelper() = default;
2443