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