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/StmtVisitor.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "llvm/ADT/SmallString.h"
24 using namespace clang;
25 
26 //===----------------------------------------------------------------------===//
27 // StmtPrinter Visitor
28 //===----------------------------------------------------------------------===//
29 
30 namespace  {
31   class StmtPrinter : public StmtVisitor<StmtPrinter> {
32     raw_ostream &OS;
33     unsigned IndentLevel;
34     clang::PrinterHelper* Helper;
35     PrintingPolicy Policy;
36 
37   public:
38     StmtPrinter(raw_ostream &os, PrinterHelper* helper,
39                 const PrintingPolicy &Policy,
40                 unsigned Indentation = 0)
41       : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy) {}
42 
43     void PrintStmt(Stmt *S) {
44       PrintStmt(S, Policy.Indentation);
45     }
46 
47     void PrintStmt(Stmt *S, int SubIndent) {
48       IndentLevel += SubIndent;
49       if (S && isa<Expr>(S)) {
50         // If this is an expr used in a stmt context, indent and newline it.
51         Indent();
52         Visit(S);
53         OS << ";\n";
54       } else if (S) {
55         Visit(S);
56       } else {
57         Indent() << "<<<NULL STATEMENT>>>\n";
58       }
59       IndentLevel -= SubIndent;
60     }
61 
62     void PrintRawCompoundStmt(CompoundStmt *S);
63     void PrintRawDecl(Decl *D);
64     void PrintRawDeclStmt(DeclStmt *S);
65     void PrintRawIfStmt(IfStmt *If);
66     void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
67     void PrintCallArgs(CallExpr *E);
68     void PrintRawSEHExceptHandler(SEHExceptStmt *S);
69     void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
70 
71     void PrintExpr(Expr *E) {
72       if (E)
73         Visit(E);
74       else
75         OS << "<null expr>";
76     }
77 
78     raw_ostream &Indent(int Delta = 0) {
79       for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
80         OS << "  ";
81       return OS;
82     }
83 
84     void Visit(Stmt* S) {
85       if (Helper && Helper->handledStmt(S,OS))
86           return;
87       else StmtVisitor<StmtPrinter>::Visit(S);
88     }
89 
90     void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
91       Indent() << "<<unknown stmt type>>\n";
92     }
93     void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
94       OS << "<<unknown expr type>>";
95     }
96     void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
97 
98 #define ABSTRACT_STMT(CLASS)
99 #define STMT(CLASS, PARENT) \
100     void Visit##CLASS(CLASS *Node);
101 #include "clang/AST/StmtNodes.inc"
102   };
103 }
104 
105 //===----------------------------------------------------------------------===//
106 //  Stmt printing methods.
107 //===----------------------------------------------------------------------===//
108 
109 /// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
110 /// with no newline after the }.
111 void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
112   OS << "{\n";
113   for (CompoundStmt::body_iterator I = Node->body_begin(), E = Node->body_end();
114        I != E; ++I)
115     PrintStmt(*I);
116 
117   Indent() << "}";
118 }
119 
120 void StmtPrinter::PrintRawDecl(Decl *D) {
121   D->print(OS, Policy, IndentLevel);
122 }
123 
124 void StmtPrinter::PrintRawDeclStmt(DeclStmt *S) {
125   DeclStmt::decl_iterator Begin = S->decl_begin(), End = S->decl_end();
126   SmallVector<Decl*, 2> Decls;
127   for ( ; Begin != End; ++Begin)
128     Decls.push_back(*Begin);
129 
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   OS << "[[";
173   bool first = true;
174   for (ArrayRef<const Attr*>::iterator it = Node->getAttrs().begin(),
175                                        end = Node->getAttrs().end();
176                                        it != end; ++it) {
177     if (!first) {
178       OS << ", ";
179       first = false;
180     }
181     // TODO: check this
182     (*it)->printPretty(OS, Policy);
183   }
184   OS << "]] ";
185   PrintStmt(Node->getSubStmt(), 0);
186 }
187 
188 void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
189   OS << "if (";
190   PrintExpr(If->getCond());
191   OS << ')';
192 
193   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
194     OS << ' ';
195     PrintRawCompoundStmt(CS);
196     OS << (If->getElse() ? ' ' : '\n');
197   } else {
198     OS << '\n';
199     PrintStmt(If->getThen());
200     if (If->getElse()) Indent();
201   }
202 
203   if (Stmt *Else = If->getElse()) {
204     OS << "else";
205 
206     if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
207       OS << ' ';
208       PrintRawCompoundStmt(CS);
209       OS << '\n';
210     } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
211       OS << ' ';
212       PrintRawIfStmt(ElseIf);
213     } else {
214       OS << '\n';
215       PrintStmt(If->getElse());
216     }
217   }
218 }
219 
220 void StmtPrinter::VisitIfStmt(IfStmt *If) {
221   Indent();
222   PrintRawIfStmt(If);
223 }
224 
225 void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
226   Indent() << "switch (";
227   PrintExpr(Node->getCond());
228   OS << ")";
229 
230   // Pretty print compoundstmt bodies (very common).
231   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
232     OS << " ";
233     PrintRawCompoundStmt(CS);
234     OS << "\n";
235   } else {
236     OS << "\n";
237     PrintStmt(Node->getBody());
238   }
239 }
240 
241 void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
242   Indent() << "while (";
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() << "}\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() << ";\n";
342 }
343 
344 void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
345   Indent() << "goto *";
346   PrintExpr(Node->getTarget());
347   OS << ";\n";
348 }
349 
350 void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
351   Indent() << "continue;\n";
352 }
353 
354 void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
355   Indent() << "break;\n";
356 }
357 
358 
359 void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
360   Indent() << "return";
361   if (Node->getRetValue()) {
362     OS << " ";
363     PrintExpr(Node->getRetValue());
364   }
365   OS << ";\n";
366 }
367 
368 
369 void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) {
370   Indent() << "asm ";
371 
372   if (Node->isVolatile())
373     OS << "volatile ";
374 
375   OS << "(";
376   VisitStringLiteral(Node->getAsmString());
377 
378   // Outputs
379   if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
380       Node->getNumClobbers() != 0)
381     OS << " : ";
382 
383   for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
384     if (i != 0)
385       OS << ", ";
386 
387     if (!Node->getOutputName(i).empty()) {
388       OS << '[';
389       OS << Node->getOutputName(i);
390       OS << "] ";
391     }
392 
393     VisitStringLiteral(Node->getOutputConstraintLiteral(i));
394     OS << " ";
395     Visit(Node->getOutputExpr(i));
396   }
397 
398   // Inputs
399   if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
400     OS << " : ";
401 
402   for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
403     if (i != 0)
404       OS << ", ";
405 
406     if (!Node->getInputName(i).empty()) {
407       OS << '[';
408       OS << Node->getInputName(i);
409       OS << "] ";
410     }
411 
412     VisitStringLiteral(Node->getInputConstraintLiteral(i));
413     OS << " ";
414     Visit(Node->getInputExpr(i));
415   }
416 
417   // Clobbers
418   if (Node->getNumClobbers() != 0)
419     OS << " : ";
420 
421   for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
422     if (i != 0)
423       OS << ", ";
424 
425     VisitStringLiteral(Node->getClobberStringLiteral(i));
426   }
427 
428   OS << ");\n";
429 }
430 
431 void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
432   // FIXME: Implement MS style inline asm statement printer.
433   Indent() << "__asm ";
434   if (Node->hasBraces())
435     OS << "{\n";
436   OS << *(Node->getAsmString()) << "\n";
437   if (Node->hasBraces())
438     Indent() << "}\n";
439 }
440 
441 void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
442   Indent() << "@try";
443   if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
444     PrintRawCompoundStmt(TS);
445     OS << "\n";
446   }
447 
448   for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
449     ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
450     Indent() << "@catch(";
451     if (catchStmt->getCatchParamDecl()) {
452       if (Decl *DS = catchStmt->getCatchParamDecl())
453         PrintRawDecl(DS);
454     }
455     OS << ")";
456     if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
457       PrintRawCompoundStmt(CS);
458       OS << "\n";
459     }
460   }
461 
462   if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
463         Node->getFinallyStmt())) {
464     Indent() << "@finally";
465     PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
466     OS << "\n";
467   }
468 }
469 
470 void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
471 }
472 
473 void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
474   Indent() << "@catch (...) { /* todo */ } \n";
475 }
476 
477 void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
478   Indent() << "@throw";
479   if (Node->getThrowExpr()) {
480     OS << " ";
481     PrintExpr(Node->getThrowExpr());
482   }
483   OS << ";\n";
484 }
485 
486 void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
487   Indent() << "@synchronized (";
488   PrintExpr(Node->getSynchExpr());
489   OS << ")";
490   PrintRawCompoundStmt(Node->getSynchBody());
491   OS << "\n";
492 }
493 
494 void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
495   Indent() << "@autoreleasepool";
496   PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
497   OS << "\n";
498 }
499 
500 void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
501   OS << "catch (";
502   if (Decl *ExDecl = Node->getExceptionDecl())
503     PrintRawDecl(ExDecl);
504   else
505     OS << "...";
506   OS << ") ";
507   PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
508 }
509 
510 void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
511   Indent();
512   PrintRawCXXCatchStmt(Node);
513   OS << "\n";
514 }
515 
516 void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
517   Indent() << "try ";
518   PrintRawCompoundStmt(Node->getTryBlock());
519   for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
520     OS << " ";
521     PrintRawCXXCatchStmt(Node->getHandler(i));
522   }
523   OS << "\n";
524 }
525 
526 void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
527   Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
528   PrintRawCompoundStmt(Node->getTryBlock());
529   SEHExceptStmt *E = Node->getExceptHandler();
530   SEHFinallyStmt *F = Node->getFinallyHandler();
531   if(E)
532     PrintRawSEHExceptHandler(E);
533   else {
534     assert(F && "Must have a finally block...");
535     PrintRawSEHFinallyStmt(F);
536   }
537   OS << "\n";
538 }
539 
540 void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
541   OS << "__finally ";
542   PrintRawCompoundStmt(Node->getBlock());
543   OS << "\n";
544 }
545 
546 void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
547   OS << "__except (";
548   VisitExpr(Node->getFilterExpr());
549   OS << ")\n";
550   PrintRawCompoundStmt(Node->getBlock());
551   OS << "\n";
552 }
553 
554 void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
555   Indent();
556   PrintRawSEHExceptHandler(Node);
557   OS << "\n";
558 }
559 
560 void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
561   Indent();
562   PrintRawSEHFinallyStmt(Node);
563   OS << "\n";
564 }
565 
566 //===----------------------------------------------------------------------===//
567 //  Expr printing methods.
568 //===----------------------------------------------------------------------===//
569 
570 void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
571   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
572     Qualifier->print(OS, Policy);
573   if (Node->hasTemplateKeyword())
574     OS << "template ";
575   OS << Node->getNameInfo();
576   if (Node->hasExplicitTemplateArgs())
577     OS << TemplateSpecializationType::PrintTemplateArgumentList(
578                                                     Node->getTemplateArgs(),
579                                                     Node->getNumTemplateArgs(),
580                                                     Policy);
581 }
582 
583 void StmtPrinter::VisitDependentScopeDeclRefExpr(
584                                            DependentScopeDeclRefExpr *Node) {
585   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
586     Qualifier->print(OS, Policy);
587   if (Node->hasTemplateKeyword())
588     OS << "template ";
589   OS << Node->getNameInfo();
590   if (Node->hasExplicitTemplateArgs())
591     OS << TemplateSpecializationType::PrintTemplateArgumentList(
592                                                    Node->getTemplateArgs(),
593                                                    Node->getNumTemplateArgs(),
594                                                    Policy);
595 }
596 
597 void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
598   if (Node->getQualifier())
599     Node->getQualifier()->print(OS, Policy);
600   if (Node->hasTemplateKeyword())
601     OS << "template ";
602   OS << Node->getNameInfo();
603   if (Node->hasExplicitTemplateArgs())
604     OS << TemplateSpecializationType::PrintTemplateArgumentList(
605                                                    Node->getTemplateArgs(),
606                                                    Node->getNumTemplateArgs(),
607                                                    Policy);
608 }
609 
610 void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
611   if (Node->getBase()) {
612     PrintExpr(Node->getBase());
613     OS << (Node->isArrow() ? "->" : ".");
614   }
615   OS << *Node->getDecl();
616 }
617 
618 void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
619   if (Node->isSuperReceiver())
620     OS << "super.";
621   else if (Node->getBase()) {
622     PrintExpr(Node->getBase());
623     OS << ".";
624   }
625 
626   if (Node->isImplicitProperty())
627     OS << Node->getImplicitPropertyGetter()->getSelector().getAsString();
628   else
629     OS << Node->getExplicitProperty()->getName();
630 }
631 
632 void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
633 
634   PrintExpr(Node->getBaseExpr());
635   OS << "[";
636   PrintExpr(Node->getKeyExpr());
637   OS << "]";
638 }
639 
640 void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
641   switch (Node->getIdentType()) {
642     default:
643       llvm_unreachable("unknown case");
644     case PredefinedExpr::Func:
645       OS << "__func__";
646       break;
647     case PredefinedExpr::Function:
648       OS << "__FUNCTION__";
649       break;
650     case PredefinedExpr::LFunction:
651       OS << "L__FUNCTION__";
652       break;
653     case PredefinedExpr::PrettyFunction:
654       OS << "__PRETTY_FUNCTION__";
655       break;
656   }
657 }
658 
659 void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
660   unsigned value = Node->getValue();
661 
662   switch (Node->getKind()) {
663   case CharacterLiteral::Ascii: break; // no prefix.
664   case CharacterLiteral::Wide:  OS << 'L'; break;
665   case CharacterLiteral::UTF16: OS << 'u'; break;
666   case CharacterLiteral::UTF32: OS << 'U'; break;
667   }
668 
669   switch (value) {
670   case '\\':
671     OS << "'\\\\'";
672     break;
673   case '\'':
674     OS << "'\\''";
675     break;
676   case '\a':
677     // TODO: K&R: the meaning of '\\a' is different in traditional C
678     OS << "'\\a'";
679     break;
680   case '\b':
681     OS << "'\\b'";
682     break;
683   // Nonstandard escape sequence.
684   /*case '\e':
685     OS << "'\\e'";
686     break;*/
687   case '\f':
688     OS << "'\\f'";
689     break;
690   case '\n':
691     OS << "'\\n'";
692     break;
693   case '\r':
694     OS << "'\\r'";
695     break;
696   case '\t':
697     OS << "'\\t'";
698     break;
699   case '\v':
700     OS << "'\\v'";
701     break;
702   default:
703     if (value < 256 && isprint(value)) {
704       OS << "'" << (char)value << "'";
705     } else if (value < 256) {
706       OS << "'\\x";
707       OS.write_hex(value) << "'";
708     } else {
709       // FIXME what to really do here?
710       OS << value;
711     }
712   }
713 }
714 
715 void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
716   bool isSigned = Node->getType()->isSignedIntegerType();
717   OS << Node->getValue().toString(10, isSigned);
718 
719   // Emit suffixes.  Integer literals are always a builtin integer type.
720   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
721   default: llvm_unreachable("Unexpected type for integer literal!");
722   // FIXME: The Short and UShort cases are to handle cases where a short
723   // integeral literal is formed during template instantiation.  They should
724   // be removed when template instantiation no longer needs integer literals.
725   case BuiltinType::Short:
726   case BuiltinType::UShort:
727   case BuiltinType::Int:       break; // no suffix.
728   case BuiltinType::UInt:      OS << 'U'; break;
729   case BuiltinType::Long:      OS << 'L'; break;
730   case BuiltinType::ULong:     OS << "UL"; break;
731   case BuiltinType::LongLong:  OS << "LL"; break;
732   case BuiltinType::ULongLong: OS << "ULL"; break;
733   case BuiltinType::Int128:    OS << "i128"; break;
734   case BuiltinType::UInt128:   OS << "Ui128"; break;
735   }
736 }
737 
738 static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
739                                  bool PrintSuffix) {
740   SmallString<16> Str;
741   Node->getValue().toString(Str);
742   OS << Str;
743   if (Str.find_first_not_of("-0123456789") == StringRef::npos)
744     OS << '.'; // Trailing dot in order to separate from ints.
745 
746   if (!PrintSuffix)
747     return;
748 
749   // Emit suffixes.  Float literals are always a builtin float type.
750   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
751   default: llvm_unreachable("Unexpected type for float literal!");
752   case BuiltinType::Half:       break; // FIXME: suffix?
753   case BuiltinType::Double:     break; // no suffix.
754   case BuiltinType::Float:      OS << 'F'; break;
755   case BuiltinType::LongDouble: OS << 'L'; break;
756   }
757 }
758 
759 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
760   PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
761 }
762 
763 void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
764   PrintExpr(Node->getSubExpr());
765   OS << "i";
766 }
767 
768 void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
769   Str->outputString(OS);
770 }
771 void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
772   OS << "(";
773   PrintExpr(Node->getSubExpr());
774   OS << ")";
775 }
776 void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
777   if (!Node->isPostfix()) {
778     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
779 
780     // Print a space if this is an "identifier operator" like __real, or if
781     // it might be concatenated incorrectly like '+'.
782     switch (Node->getOpcode()) {
783     default: break;
784     case UO_Real:
785     case UO_Imag:
786     case UO_Extension:
787       OS << ' ';
788       break;
789     case UO_Plus:
790     case UO_Minus:
791       if (isa<UnaryOperator>(Node->getSubExpr()))
792         OS << ' ';
793       break;
794     }
795   }
796   PrintExpr(Node->getSubExpr());
797 
798   if (Node->isPostfix())
799     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
800 }
801 
802 void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
803   OS << "__builtin_offsetof(";
804   OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
805   bool PrintedSomething = false;
806   for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
807     OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
808     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
809       // Array node
810       OS << "[";
811       PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
812       OS << "]";
813       PrintedSomething = true;
814       continue;
815     }
816 
817     // Skip implicit base indirections.
818     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
819       continue;
820 
821     // Field or identifier node.
822     IdentifierInfo *Id = ON.getFieldName();
823     if (!Id)
824       continue;
825 
826     if (PrintedSomething)
827       OS << ".";
828     else
829       PrintedSomething = true;
830     OS << Id->getName();
831   }
832   OS << ")";
833 }
834 
835 void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
836   switch(Node->getKind()) {
837   case UETT_SizeOf:
838     OS << "sizeof";
839     break;
840   case UETT_AlignOf:
841     if (Policy.LangOpts.CPlusPlus)
842       OS << "alignof";
843     else if (Policy.LangOpts.C11)
844       OS << "_Alignof";
845     else
846       OS << "__alignof";
847     break;
848   case UETT_VecStep:
849     OS << "vec_step";
850     break;
851   }
852   if (Node->isArgumentType())
853     OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
854   else {
855     OS << " ";
856     PrintExpr(Node->getArgumentExpr());
857   }
858 }
859 
860 void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
861   OS << "_Generic(";
862   PrintExpr(Node->getControllingExpr());
863   for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
864     OS << ", ";
865     QualType T = Node->getAssocType(i);
866     if (T.isNull())
867       OS << "default";
868     else
869       OS << T.getAsString(Policy);
870     OS << ": ";
871     PrintExpr(Node->getAssocExpr(i));
872   }
873   OS << ")";
874 }
875 
876 void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
877   PrintExpr(Node->getLHS());
878   OS << "[";
879   PrintExpr(Node->getRHS());
880   OS << "]";
881 }
882 
883 void StmtPrinter::PrintCallArgs(CallExpr *Call) {
884   for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
885     if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
886       // Don't print any defaulted arguments
887       break;
888     }
889 
890     if (i) OS << ", ";
891     PrintExpr(Call->getArg(i));
892   }
893 }
894 
895 void StmtPrinter::VisitCallExpr(CallExpr *Call) {
896   PrintExpr(Call->getCallee());
897   OS << "(";
898   PrintCallArgs(Call);
899   OS << ")";
900 }
901 void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
902   // FIXME: Suppress printing implicit bases (like "this")
903   PrintExpr(Node->getBase());
904   if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
905     if (FD->isAnonymousStructOrUnion())
906       return;
907   OS << (Node->isArrow() ? "->" : ".");
908   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
909     Qualifier->print(OS, Policy);
910   if (Node->hasTemplateKeyword())
911     OS << "template ";
912   OS << Node->getMemberNameInfo();
913   if (Node->hasExplicitTemplateArgs())
914     OS << TemplateSpecializationType::PrintTemplateArgumentList(
915                                                     Node->getTemplateArgs(),
916                                                     Node->getNumTemplateArgs(),
917                                                                 Policy);
918 }
919 void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
920   PrintExpr(Node->getBase());
921   OS << (Node->isArrow() ? "->isa" : ".isa");
922 }
923 
924 void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
925   PrintExpr(Node->getBase());
926   OS << ".";
927   OS << Node->getAccessor().getName();
928 }
929 void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
930   OS << "(" << Node->getType().getAsString(Policy) << ")";
931   PrintExpr(Node->getSubExpr());
932 }
933 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
934   OS << "(" << Node->getType().getAsString(Policy) << ")";
935   PrintExpr(Node->getInitializer());
936 }
937 void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
938   // No need to print anything, simply forward to the sub expression.
939   PrintExpr(Node->getSubExpr());
940 }
941 void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
942   PrintExpr(Node->getLHS());
943   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
944   PrintExpr(Node->getRHS());
945 }
946 void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
947   PrintExpr(Node->getLHS());
948   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
949   PrintExpr(Node->getRHS());
950 }
951 void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
952   PrintExpr(Node->getCond());
953   OS << " ? ";
954   PrintExpr(Node->getLHS());
955   OS << " : ";
956   PrintExpr(Node->getRHS());
957 }
958 
959 // GNU extensions.
960 
961 void
962 StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
963   PrintExpr(Node->getCommon());
964   OS << " ?: ";
965   PrintExpr(Node->getFalseExpr());
966 }
967 void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
968   OS << "&&" << Node->getLabel()->getName();
969 }
970 
971 void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
972   OS << "(";
973   PrintRawCompoundStmt(E->getSubStmt());
974   OS << ")";
975 }
976 
977 void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
978   OS << "__builtin_choose_expr(";
979   PrintExpr(Node->getCond());
980   OS << ", ";
981   PrintExpr(Node->getLHS());
982   OS << ", ";
983   PrintExpr(Node->getRHS());
984   OS << ")";
985 }
986 
987 void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
988   OS << "__null";
989 }
990 
991 void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
992   OS << "__builtin_shufflevector(";
993   for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
994     if (i) OS << ", ";
995     PrintExpr(Node->getExpr(i));
996   }
997   OS << ")";
998 }
999 
1000 void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1001   if (Node->getSyntacticForm()) {
1002     Visit(Node->getSyntacticForm());
1003     return;
1004   }
1005 
1006   OS << "{ ";
1007   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1008     if (i) OS << ", ";
1009     if (Node->getInit(i))
1010       PrintExpr(Node->getInit(i));
1011     else
1012       OS << "0";
1013   }
1014   OS << " }";
1015 }
1016 
1017 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1018   OS << "( ";
1019   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1020     if (i) OS << ", ";
1021     PrintExpr(Node->getExpr(i));
1022   }
1023   OS << " )";
1024 }
1025 
1026 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1027   for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1028                       DEnd = Node->designators_end();
1029        D != DEnd; ++D) {
1030     if (D->isFieldDesignator()) {
1031       if (D->getDotLoc().isInvalid())
1032         OS << D->getFieldName()->getName() << ":";
1033       else
1034         OS << "." << D->getFieldName()->getName();
1035     } else {
1036       OS << "[";
1037       if (D->isArrayDesignator()) {
1038         PrintExpr(Node->getArrayIndex(*D));
1039       } else {
1040         PrintExpr(Node->getArrayRangeStart(*D));
1041         OS << " ... ";
1042         PrintExpr(Node->getArrayRangeEnd(*D));
1043       }
1044       OS << "]";
1045     }
1046   }
1047 
1048   OS << " = ";
1049   PrintExpr(Node->getInit());
1050 }
1051 
1052 void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1053   if (Policy.LangOpts.CPlusPlus)
1054     OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
1055   else {
1056     OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
1057     if (Node->getType()->isRecordType())
1058       OS << "{}";
1059     else
1060       OS << 0;
1061   }
1062 }
1063 
1064 void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1065   OS << "__builtin_va_arg(";
1066   PrintExpr(Node->getSubExpr());
1067   OS << ", ";
1068   OS << Node->getType().getAsString(Policy);
1069   OS << ")";
1070 }
1071 
1072 void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1073   PrintExpr(Node->getSyntacticForm());
1074 }
1075 
1076 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1077   const char *Name = 0;
1078   switch (Node->getOp()) {
1079 #define BUILTIN(ID, TYPE, ATTRS)
1080 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1081   case AtomicExpr::AO ## ID: \
1082     Name = #ID "("; \
1083     break;
1084 #include "clang/Basic/Builtins.def"
1085   }
1086   OS << Name;
1087 
1088   // AtomicExpr stores its subexpressions in a permuted order.
1089   PrintExpr(Node->getPtr());
1090   OS << ", ";
1091   if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1092       Node->getOp() != AtomicExpr::AO__atomic_load_n) {
1093     PrintExpr(Node->getVal1());
1094     OS << ", ";
1095   }
1096   if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1097       Node->isCmpXChg()) {
1098     PrintExpr(Node->getVal2());
1099     OS << ", ";
1100   }
1101   if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1102       Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1103     PrintExpr(Node->getWeak());
1104     OS << ", ";
1105   }
1106   if (Node->getOp() != AtomicExpr::AO__c11_atomic_init)
1107     PrintExpr(Node->getOrder());
1108   if (Node->isCmpXChg()) {
1109     OS << ", ";
1110     PrintExpr(Node->getOrderFail());
1111   }
1112   OS << ")";
1113 }
1114 
1115 // C++
1116 void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1117   const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1118     "",
1119 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1120     Spelling,
1121 #include "clang/Basic/OperatorKinds.def"
1122   };
1123 
1124   OverloadedOperatorKind Kind = Node->getOperator();
1125   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1126     if (Node->getNumArgs() == 1) {
1127       OS << OpStrings[Kind] << ' ';
1128       PrintExpr(Node->getArg(0));
1129     } else {
1130       PrintExpr(Node->getArg(0));
1131       OS << ' ' << OpStrings[Kind];
1132     }
1133   } else if (Kind == OO_Call) {
1134     PrintExpr(Node->getArg(0));
1135     OS << '(';
1136     for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1137       if (ArgIdx > 1)
1138         OS << ", ";
1139       if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1140         PrintExpr(Node->getArg(ArgIdx));
1141     }
1142     OS << ')';
1143   } else if (Kind == OO_Subscript) {
1144     PrintExpr(Node->getArg(0));
1145     OS << '[';
1146     PrintExpr(Node->getArg(1));
1147     OS << ']';
1148   } else if (Node->getNumArgs() == 1) {
1149     OS << OpStrings[Kind] << ' ';
1150     PrintExpr(Node->getArg(0));
1151   } else if (Node->getNumArgs() == 2) {
1152     PrintExpr(Node->getArg(0));
1153     OS << ' ' << OpStrings[Kind] << ' ';
1154     PrintExpr(Node->getArg(1));
1155   } else {
1156     llvm_unreachable("unknown overloaded operator");
1157   }
1158 }
1159 
1160 void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1161   VisitCallExpr(cast<CallExpr>(Node));
1162 }
1163 
1164 void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1165   PrintExpr(Node->getCallee());
1166   OS << "<<<";
1167   PrintCallArgs(Node->getConfig());
1168   OS << ">>>(";
1169   PrintCallArgs(Node);
1170   OS << ")";
1171 }
1172 
1173 void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1174   OS << Node->getCastName() << '<';
1175   OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1176   PrintExpr(Node->getSubExpr());
1177   OS << ")";
1178 }
1179 
1180 void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1181   VisitCXXNamedCastExpr(Node);
1182 }
1183 
1184 void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1185   VisitCXXNamedCastExpr(Node);
1186 }
1187 
1188 void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1189   VisitCXXNamedCastExpr(Node);
1190 }
1191 
1192 void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1193   VisitCXXNamedCastExpr(Node);
1194 }
1195 
1196 void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1197   OS << "typeid(";
1198   if (Node->isTypeOperand()) {
1199     OS << Node->getTypeOperand().getAsString(Policy);
1200   } else {
1201     PrintExpr(Node->getExprOperand());
1202   }
1203   OS << ")";
1204 }
1205 
1206 void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1207   OS << "__uuidof(";
1208   if (Node->isTypeOperand()) {
1209     OS << Node->getTypeOperand().getAsString(Policy);
1210   } else {
1211     PrintExpr(Node->getExprOperand());
1212   }
1213   OS << ")";
1214 }
1215 
1216 void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1217   switch (Node->getLiteralOperatorKind()) {
1218   case UserDefinedLiteral::LOK_Raw:
1219     OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1220     break;
1221   case UserDefinedLiteral::LOK_Template: {
1222     DeclRefExpr *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1223     const TemplateArgumentList *Args =
1224       cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1225     assert(Args);
1226     const TemplateArgument &Pack = Args->get(0);
1227     for (TemplateArgument::pack_iterator I = Pack.pack_begin(),
1228                                          E = Pack.pack_end(); I != E; ++I) {
1229       char C = (char)I->getAsIntegral().getZExtValue();
1230       OS << C;
1231     }
1232     break;
1233   }
1234   case UserDefinedLiteral::LOK_Integer: {
1235     // Print integer literal without suffix.
1236     IntegerLiteral *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1237     OS << Int->getValue().toString(10, /*isSigned*/false);
1238     break;
1239   }
1240   case UserDefinedLiteral::LOK_Floating: {
1241     // Print floating literal without suffix.
1242     FloatingLiteral *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1243     PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1244     break;
1245   }
1246   case UserDefinedLiteral::LOK_String:
1247   case UserDefinedLiteral::LOK_Character:
1248     PrintExpr(Node->getCookedLiteral());
1249     break;
1250   }
1251   OS << Node->getUDSuffix()->getName();
1252 }
1253 
1254 void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1255   OS << (Node->getValue() ? "true" : "false");
1256 }
1257 
1258 void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1259   OS << "nullptr";
1260 }
1261 
1262 void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1263   OS << "this";
1264 }
1265 
1266 void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1267   if (Node->getSubExpr() == 0)
1268     OS << "throw";
1269   else {
1270     OS << "throw ";
1271     PrintExpr(Node->getSubExpr());
1272   }
1273 }
1274 
1275 void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1276   // Nothing to print: we picked up the default argument
1277 }
1278 
1279 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1280   OS << Node->getType().getAsString(Policy);
1281   OS << "(";
1282   PrintExpr(Node->getSubExpr());
1283   OS << ")";
1284 }
1285 
1286 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1287   PrintExpr(Node->getSubExpr());
1288 }
1289 
1290 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1291   OS << Node->getType().getAsString(Policy);
1292   OS << "(";
1293   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1294                                          ArgEnd = Node->arg_end();
1295        Arg != ArgEnd; ++Arg) {
1296     if (Arg != Node->arg_begin())
1297       OS << ", ";
1298     PrintExpr(*Arg);
1299   }
1300   OS << ")";
1301 }
1302 
1303 void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1304   OS << '[';
1305   bool NeedComma = false;
1306   switch (Node->getCaptureDefault()) {
1307   case LCD_None:
1308     break;
1309 
1310   case LCD_ByCopy:
1311     OS << '=';
1312     NeedComma = true;
1313     break;
1314 
1315   case LCD_ByRef:
1316     OS << '&';
1317     NeedComma = true;
1318     break;
1319   }
1320   for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1321                                  CEnd = Node->explicit_capture_end();
1322        C != CEnd;
1323        ++C) {
1324     if (NeedComma)
1325       OS << ", ";
1326     NeedComma = true;
1327 
1328     switch (C->getCaptureKind()) {
1329     case LCK_This:
1330       OS << "this";
1331       break;
1332 
1333     case LCK_ByRef:
1334       if (Node->getCaptureDefault() != LCD_ByRef)
1335         OS << '&';
1336       OS << C->getCapturedVar()->getName();
1337       break;
1338 
1339     case LCK_ByCopy:
1340       if (Node->getCaptureDefault() != LCD_ByCopy)
1341         OS << '=';
1342       OS << C->getCapturedVar()->getName();
1343       break;
1344     }
1345   }
1346   OS << ']';
1347 
1348   if (Node->hasExplicitParameters()) {
1349     OS << " (";
1350     CXXMethodDecl *Method = Node->getCallOperator();
1351     NeedComma = false;
1352     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
1353                                     PEnd = Method->param_end();
1354          P != PEnd; ++P) {
1355       if (NeedComma) {
1356         OS << ", ";
1357       } else {
1358         NeedComma = true;
1359       }
1360       std::string ParamStr = (*P)->getNameAsString();
1361       (*P)->getOriginalType().getAsStringInternal(ParamStr, Policy);
1362       OS << ParamStr;
1363     }
1364     if (Method->isVariadic()) {
1365       if (NeedComma)
1366         OS << ", ";
1367       OS << "...";
1368     }
1369     OS << ')';
1370 
1371     if (Node->isMutable())
1372       OS << " mutable";
1373 
1374     const FunctionProtoType *Proto
1375       = Method->getType()->getAs<FunctionProtoType>();
1376     {
1377       std::string ExceptionSpec;
1378       Proto->printExceptionSpecification(ExceptionSpec, Policy);
1379       OS << ExceptionSpec;
1380     }
1381 
1382     // FIXME: Attributes
1383 
1384     // Print the trailing return type if it was specified in the source.
1385     if (Node->hasExplicitResultType())
1386       OS << " -> " << Proto->getResultType().getAsString(Policy);
1387   }
1388 
1389   // Print the body.
1390   CompoundStmt *Body = Node->getBody();
1391   OS << ' ';
1392   PrintStmt(Body);
1393 }
1394 
1395 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1396   if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1397     OS << TSInfo->getType().getAsString(Policy) << "()";
1398   else
1399     OS << Node->getType().getAsString(Policy) << "()";
1400 }
1401 
1402 void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1403   if (E->isGlobalNew())
1404     OS << "::";
1405   OS << "new ";
1406   unsigned NumPlace = E->getNumPlacementArgs();
1407   if (NumPlace > 0) {
1408     OS << "(";
1409     PrintExpr(E->getPlacementArg(0));
1410     for (unsigned i = 1; i < NumPlace; ++i) {
1411       OS << ", ";
1412       PrintExpr(E->getPlacementArg(i));
1413     }
1414     OS << ") ";
1415   }
1416   if (E->isParenTypeId())
1417     OS << "(";
1418   std::string TypeS;
1419   if (Expr *Size = E->getArraySize()) {
1420     llvm::raw_string_ostream s(TypeS);
1421     Size->printPretty(s, Helper, Policy);
1422     s.flush();
1423     TypeS = "[" + TypeS + "]";
1424   }
1425   E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1426   OS << TypeS;
1427   if (E->isParenTypeId())
1428     OS << ")";
1429 
1430   CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
1431   if (InitStyle) {
1432     if (InitStyle == CXXNewExpr::CallInit)
1433       OS << "(";
1434     PrintExpr(E->getInitializer());
1435     if (InitStyle == CXXNewExpr::CallInit)
1436       OS << ")";
1437   }
1438 }
1439 
1440 void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1441   if (E->isGlobalDelete())
1442     OS << "::";
1443   OS << "delete ";
1444   if (E->isArrayForm())
1445     OS << "[] ";
1446   PrintExpr(E->getArgument());
1447 }
1448 
1449 void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1450   PrintExpr(E->getBase());
1451   if (E->isArrow())
1452     OS << "->";
1453   else
1454     OS << '.';
1455   if (E->getQualifier())
1456     E->getQualifier()->print(OS, Policy);
1457 
1458   std::string TypeS;
1459   if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1460     OS << II->getName();
1461   else
1462     E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1463   OS << TypeS;
1464 }
1465 
1466 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1467   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1468     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1469       // Don't print any defaulted arguments
1470       break;
1471     }
1472 
1473     if (i) OS << ", ";
1474     PrintExpr(E->getArg(i));
1475   }
1476 }
1477 
1478 void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1479   // Just forward to the sub expression.
1480   PrintExpr(E->getSubExpr());
1481 }
1482 
1483 void
1484 StmtPrinter::VisitCXXUnresolvedConstructExpr(
1485                                            CXXUnresolvedConstructExpr *Node) {
1486   OS << Node->getTypeAsWritten().getAsString(Policy);
1487   OS << "(";
1488   for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1489                                              ArgEnd = Node->arg_end();
1490        Arg != ArgEnd; ++Arg) {
1491     if (Arg != Node->arg_begin())
1492       OS << ", ";
1493     PrintExpr(*Arg);
1494   }
1495   OS << ")";
1496 }
1497 
1498 void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1499                                          CXXDependentScopeMemberExpr *Node) {
1500   if (!Node->isImplicitAccess()) {
1501     PrintExpr(Node->getBase());
1502     OS << (Node->isArrow() ? "->" : ".");
1503   }
1504   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1505     Qualifier->print(OS, Policy);
1506   if (Node->hasTemplateKeyword())
1507     OS << "template ";
1508   OS << Node->getMemberNameInfo();
1509   if (Node->hasExplicitTemplateArgs()) {
1510     OS << TemplateSpecializationType::PrintTemplateArgumentList(
1511                                                     Node->getTemplateArgs(),
1512                                                     Node->getNumTemplateArgs(),
1513                                                     Policy);
1514   }
1515 }
1516 
1517 void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1518   if (!Node->isImplicitAccess()) {
1519     PrintExpr(Node->getBase());
1520     OS << (Node->isArrow() ? "->" : ".");
1521   }
1522   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1523     Qualifier->print(OS, Policy);
1524   if (Node->hasTemplateKeyword())
1525     OS << "template ";
1526   OS << Node->getMemberNameInfo();
1527   if (Node->hasExplicitTemplateArgs()) {
1528     OS << TemplateSpecializationType::PrintTemplateArgumentList(
1529                                                     Node->getTemplateArgs(),
1530                                                     Node->getNumTemplateArgs(),
1531                                                     Policy);
1532   }
1533 }
1534 
1535 static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1536   switch (UTT) {
1537   case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1538   case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1539   case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1540   case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1541   case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1542   case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1543   case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1544   case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1545   case UTT_IsAbstract:            return "__is_abstract";
1546   case UTT_IsArithmetic:            return "__is_arithmetic";
1547   case UTT_IsArray:                 return "__is_array";
1548   case UTT_IsClass:               return "__is_class";
1549   case UTT_IsCompleteType:          return "__is_complete_type";
1550   case UTT_IsCompound:              return "__is_compound";
1551   case UTT_IsConst:                 return "__is_const";
1552   case UTT_IsEmpty:               return "__is_empty";
1553   case UTT_IsEnum:                return "__is_enum";
1554   case UTT_IsFinal:                 return "__is_final";
1555   case UTT_IsFloatingPoint:         return "__is_floating_point";
1556   case UTT_IsFunction:              return "__is_function";
1557   case UTT_IsFundamental:           return "__is_fundamental";
1558   case UTT_IsIntegral:              return "__is_integral";
1559   case UTT_IsInterfaceClass:        return "__is_interface_class";
1560   case UTT_IsLiteral:               return "__is_literal";
1561   case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1562   case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1563   case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1564   case UTT_IsMemberPointer:         return "__is_member_pointer";
1565   case UTT_IsObject:                return "__is_object";
1566   case UTT_IsPOD:                 return "__is_pod";
1567   case UTT_IsPointer:               return "__is_pointer";
1568   case UTT_IsPolymorphic:         return "__is_polymorphic";
1569   case UTT_IsReference:             return "__is_reference";
1570   case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1571   case UTT_IsScalar:                return "__is_scalar";
1572   case UTT_IsSigned:                return "__is_signed";
1573   case UTT_IsStandardLayout:        return "__is_standard_layout";
1574   case UTT_IsTrivial:               return "__is_trivial";
1575   case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1576   case UTT_IsUnion:               return "__is_union";
1577   case UTT_IsUnsigned:              return "__is_unsigned";
1578   case UTT_IsVoid:                  return "__is_void";
1579   case UTT_IsVolatile:              return "__is_volatile";
1580   }
1581   llvm_unreachable("Type trait not covered by switch statement");
1582 }
1583 
1584 static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1585   switch (BTT) {
1586   case BTT_IsBaseOf:              return "__is_base_of";
1587   case BTT_IsConvertible:         return "__is_convertible";
1588   case BTT_IsSame:                return "__is_same";
1589   case BTT_TypeCompatible:        return "__builtin_types_compatible_p";
1590   case BTT_IsConvertibleTo:       return "__is_convertible_to";
1591   case BTT_IsTriviallyAssignable: return "__is_trivially_assignable";
1592   }
1593   llvm_unreachable("Binary type trait not covered by switch");
1594 }
1595 
1596 static const char *getTypeTraitName(TypeTrait TT) {
1597   switch (TT) {
1598   case clang::TT_IsTriviallyConstructible:return "__is_trivially_constructible";
1599   }
1600   llvm_unreachable("Type trait not covered by switch");
1601 }
1602 
1603 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1604   switch (ATT) {
1605   case ATT_ArrayRank:        return "__array_rank";
1606   case ATT_ArrayExtent:      return "__array_extent";
1607   }
1608   llvm_unreachable("Array type trait not covered by switch");
1609 }
1610 
1611 static const char *getExpressionTraitName(ExpressionTrait ET) {
1612   switch (ET) {
1613   case ET_IsLValueExpr:      return "__is_lvalue_expr";
1614   case ET_IsRValueExpr:      return "__is_rvalue_expr";
1615   }
1616   llvm_unreachable("Expression type trait not covered by switch");
1617 }
1618 
1619 void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1620   OS << getTypeTraitName(E->getTrait()) << "("
1621      << E->getQueriedType().getAsString(Policy) << ")";
1622 }
1623 
1624 void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1625   OS << getTypeTraitName(E->getTrait()) << "("
1626      << E->getLhsType().getAsString(Policy) << ","
1627      << E->getRhsType().getAsString(Policy) << ")";
1628 }
1629 
1630 void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
1631   OS << getTypeTraitName(E->getTrait()) << "(";
1632   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
1633     if (I > 0)
1634       OS << ", ";
1635     OS << E->getArg(I)->getType().getAsString(Policy);
1636   }
1637   OS << ")";
1638 }
1639 
1640 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1641   OS << getTypeTraitName(E->getTrait()) << "("
1642      << E->getQueriedType().getAsString(Policy) << ")";
1643 }
1644 
1645 void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1646     OS << getExpressionTraitName(E->getTrait()) << "(";
1647     PrintExpr(E->getQueriedExpression());
1648     OS << ")";
1649 }
1650 
1651 void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1652   OS << "noexcept(";
1653   PrintExpr(E->getOperand());
1654   OS << ")";
1655 }
1656 
1657 void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1658   PrintExpr(E->getPattern());
1659   OS << "...";
1660 }
1661 
1662 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1663   OS << "sizeof...(" << *E->getPack() << ")";
1664 }
1665 
1666 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1667                                        SubstNonTypeTemplateParmPackExpr *Node) {
1668   OS << *Node->getParameterPack();
1669 }
1670 
1671 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1672                                        SubstNonTypeTemplateParmExpr *Node) {
1673   Visit(Node->getReplacement());
1674 }
1675 
1676 void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
1677   OS << *E->getParameterPack();
1678 }
1679 
1680 void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1681   PrintExpr(Node->GetTemporaryExpr());
1682 }
1683 
1684 // Obj-C
1685 
1686 void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1687   OS << "@";
1688   VisitStringLiteral(Node->getString());
1689 }
1690 
1691 void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1692   OS << "@";
1693   Visit(E->getSubExpr());
1694 }
1695 
1696 void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1697   OS << "@[ ";
1698   StmtRange ch = E->children();
1699   if (ch.first != ch.second) {
1700     while (1) {
1701       Visit(*ch.first);
1702       ++ch.first;
1703       if (ch.first == ch.second) break;
1704       OS << ", ";
1705     }
1706   }
1707   OS << " ]";
1708 }
1709 
1710 void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1711   OS << "@{ ";
1712   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
1713     if (I > 0)
1714       OS << ", ";
1715 
1716     ObjCDictionaryElement Element = E->getKeyValueElement(I);
1717     Visit(Element.Key);
1718     OS << " : ";
1719     Visit(Element.Value);
1720     if (Element.isPackExpansion())
1721       OS << "...";
1722   }
1723   OS << " }";
1724 }
1725 
1726 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1727   OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1728 }
1729 
1730 void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1731   OS << "@selector(" << Node->getSelector().getAsString() << ')';
1732 }
1733 
1734 void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1735   OS << "@protocol(" << *Node->getProtocol() << ')';
1736 }
1737 
1738 void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1739   OS << "[";
1740   switch (Mess->getReceiverKind()) {
1741   case ObjCMessageExpr::Instance:
1742     PrintExpr(Mess->getInstanceReceiver());
1743     break;
1744 
1745   case ObjCMessageExpr::Class:
1746     OS << Mess->getClassReceiver().getAsString(Policy);
1747     break;
1748 
1749   case ObjCMessageExpr::SuperInstance:
1750   case ObjCMessageExpr::SuperClass:
1751     OS << "Super";
1752     break;
1753   }
1754 
1755   OS << ' ';
1756   Selector selector = Mess->getSelector();
1757   if (selector.isUnarySelector()) {
1758     OS << selector.getNameForSlot(0);
1759   } else {
1760     for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1761       if (i < selector.getNumArgs()) {
1762         if (i > 0) OS << ' ';
1763         if (selector.getIdentifierInfoForSlot(i))
1764           OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1765         else
1766            OS << ":";
1767       }
1768       else OS << ", "; // Handle variadic methods.
1769 
1770       PrintExpr(Mess->getArg(i));
1771     }
1772   }
1773   OS << "]";
1774 }
1775 
1776 void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
1777   OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
1778 }
1779 
1780 void
1781 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1782   PrintExpr(E->getSubExpr());
1783 }
1784 
1785 void
1786 StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1787   OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1788      << ")";
1789   PrintExpr(E->getSubExpr());
1790 }
1791 
1792 void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1793   BlockDecl *BD = Node->getBlockDecl();
1794   OS << "^";
1795 
1796   const FunctionType *AFT = Node->getFunctionType();
1797 
1798   if (isa<FunctionNoProtoType>(AFT)) {
1799     OS << "()";
1800   } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1801     OS << '(';
1802     std::string ParamStr;
1803     for (BlockDecl::param_iterator AI = BD->param_begin(),
1804          E = BD->param_end(); AI != E; ++AI) {
1805       if (AI != BD->param_begin()) OS << ", ";
1806       ParamStr = (*AI)->getNameAsString();
1807       (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1808       OS << ParamStr;
1809     }
1810 
1811     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1812     if (FT->isVariadic()) {
1813       if (!BD->param_empty()) OS << ", ";
1814       OS << "...";
1815     }
1816     OS << ')';
1817   }
1818 }
1819 
1820 void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
1821   PrintExpr(Node->getSourceExpr());
1822 }
1823 
1824 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1825   OS << "__builtin_astype(";
1826   PrintExpr(Node->getSrcExpr());
1827   OS << ", " << Node->getType().getAsString();
1828   OS << ")";
1829 }
1830 
1831 //===----------------------------------------------------------------------===//
1832 // Stmt method implementations
1833 //===----------------------------------------------------------------------===//
1834 
1835 void Stmt::dumpPretty(ASTContext &Context) const {
1836   printPretty(llvm::errs(), 0, PrintingPolicy(Context.getLangOpts()));
1837 }
1838 
1839 void Stmt::printPretty(raw_ostream &OS,
1840                        PrinterHelper *Helper,
1841                        const PrintingPolicy &Policy,
1842                        unsigned Indentation) const {
1843   if (this == 0) {
1844     OS << "<NULL>";
1845     return;
1846   }
1847 
1848   if (Policy.DumpSourceManager) {
1849     dump(OS, *Policy.DumpSourceManager);
1850     return;
1851   }
1852 
1853   StmtPrinter P(OS, Helper, Policy, Indentation);
1854   P.Visit(const_cast<Stmt*>(this));
1855 }
1856 
1857 //===----------------------------------------------------------------------===//
1858 // PrinterHelper
1859 //===----------------------------------------------------------------------===//
1860 
1861 // Implement virtual destructor.
1862 PrinterHelper::~PrinterHelper() {}
1863