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