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