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