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 "llvm/Support/Format.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.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" << llvm::format("%x", value) << "'";
670     } else {
671       // FIXME what to really do here?
672       OS << value;
673     }
674   }
675 }
676 
677 void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
678   bool isSigned = Node->getType()->isSignedIntegerType();
679   OS << Node->getValue().toString(10, isSigned);
680 
681   // Emit suffixes.  Integer literals are always a builtin integer type.
682   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
683   default: llvm_unreachable("Unexpected type for integer literal!");
684   // FIXME: The Short and UShort cases are to handle cases where a short
685   // integeral literal is formed during template instantiation.  They should
686   // be removed when template instantiation no longer needs integer literals.
687   case BuiltinType::Short:
688   case BuiltinType::UShort:
689   case BuiltinType::Int:       break; // no suffix.
690   case BuiltinType::UInt:      OS << 'U'; break;
691   case BuiltinType::Long:      OS << 'L'; break;
692   case BuiltinType::ULong:     OS << "UL"; break;
693   case BuiltinType::LongLong:  OS << "LL"; break;
694   case BuiltinType::ULongLong: OS << "ULL"; break;
695   case BuiltinType::Int128:    OS << "i128"; break;
696   case BuiltinType::UInt128:   OS << "Ui128"; break;
697   }
698 }
699 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
700   llvm::SmallString<16> Str;
701   Node->getValue().toString(Str);
702   OS << Str;
703 }
704 
705 void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
706   PrintExpr(Node->getSubExpr());
707   OS << "i";
708 }
709 
710 void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
711   switch (Str->getKind()) {
712   case StringLiteral::Ascii: break; // no prefix.
713   case StringLiteral::Wide:  OS << 'L'; break;
714   case StringLiteral::UTF8:  OS << "u8"; break;
715   case StringLiteral::UTF16: OS << 'u'; break;
716   case StringLiteral::UTF32: OS << 'U'; break;
717   }
718   OS << '"';
719   static char Hex[] = "0123456789ABCDEF";
720 
721   for (unsigned I = 0, N = Str->getLength(); I != N; ++I) {
722     switch (uint32_t Char = Str->getCodeUnit(I)) {
723     default:
724       // FIXME: Is this the best way to print wchar_t?
725       if (Char > 0xff) {
726         assert(Char <= 0x10ffff && "invalid unicode codepoint");
727         if (Char > 0xffff)
728           OS << "\\U00"
729              << Hex[(Char >> 20) & 15]
730              << Hex[(Char >> 16) & 15];
731         else
732           OS << "\\u";
733         OS << Hex[(Char >> 12) & 15]
734            << Hex[(Char >>  8) & 15]
735            << Hex[(Char >>  4) & 15]
736            << Hex[(Char >>  0) & 15];
737         break;
738       }
739       if (Char <= 0xff && isprint(Char))
740         OS << (char)Char;
741       else  // Output anything hard as an octal escape.
742         OS << '\\'
743         << (char)('0'+ ((Char >> 6) & 7))
744         << (char)('0'+ ((Char >> 3) & 7))
745         << (char)('0'+ ((Char >> 0) & 7));
746       break;
747     // Handle some common non-printable cases to make dumps prettier.
748     case '\\': OS << "\\\\"; break;
749     case '"': OS << "\\\""; break;
750     case '\n': OS << "\\n"; break;
751     case '\t': OS << "\\t"; break;
752     case '\a': OS << "\\a"; break;
753     case '\b': OS << "\\b"; break;
754     }
755   }
756   OS << '"';
757 }
758 void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
759   OS << "(";
760   PrintExpr(Node->getSubExpr());
761   OS << ")";
762 }
763 void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
764   if (!Node->isPostfix()) {
765     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
766 
767     // Print a space if this is an "identifier operator" like __real, or if
768     // it might be concatenated incorrectly like '+'.
769     switch (Node->getOpcode()) {
770     default: break;
771     case UO_Real:
772     case UO_Imag:
773     case UO_Extension:
774       OS << ' ';
775       break;
776     case UO_Plus:
777     case UO_Minus:
778       if (isa<UnaryOperator>(Node->getSubExpr()))
779         OS << ' ';
780       break;
781     }
782   }
783   PrintExpr(Node->getSubExpr());
784 
785   if (Node->isPostfix())
786     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
787 }
788 
789 void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
790   OS << "__builtin_offsetof(";
791   OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
792   bool PrintedSomething = false;
793   for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
794     OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
795     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
796       // Array node
797       OS << "[";
798       PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
799       OS << "]";
800       PrintedSomething = true;
801       continue;
802     }
803 
804     // Skip implicit base indirections.
805     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
806       continue;
807 
808     // Field or identifier node.
809     IdentifierInfo *Id = ON.getFieldName();
810     if (!Id)
811       continue;
812 
813     if (PrintedSomething)
814       OS << ".";
815     else
816       PrintedSomething = true;
817     OS << Id->getName();
818   }
819   OS << ")";
820 }
821 
822 void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
823   switch(Node->getKind()) {
824   case UETT_SizeOf:
825     OS << "sizeof";
826     break;
827   case UETT_AlignOf:
828     OS << "__alignof";
829     break;
830   case UETT_VecStep:
831     OS << "vec_step";
832     break;
833   }
834   if (Node->isArgumentType())
835     OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
836   else {
837     OS << " ";
838     PrintExpr(Node->getArgumentExpr());
839   }
840 }
841 
842 void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
843   OS << "_Generic(";
844   PrintExpr(Node->getControllingExpr());
845   for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
846     OS << ", ";
847     QualType T = Node->getAssocType(i);
848     if (T.isNull())
849       OS << "default";
850     else
851       OS << T.getAsString(Policy);
852     OS << ": ";
853     PrintExpr(Node->getAssocExpr(i));
854   }
855   OS << ")";
856 }
857 
858 void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
859   PrintExpr(Node->getLHS());
860   OS << "[";
861   PrintExpr(Node->getRHS());
862   OS << "]";
863 }
864 
865 void StmtPrinter::PrintCallArgs(CallExpr *Call) {
866   for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
867     if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
868       // Don't print any defaulted arguments
869       break;
870     }
871 
872     if (i) OS << ", ";
873     PrintExpr(Call->getArg(i));
874   }
875 }
876 
877 void StmtPrinter::VisitCallExpr(CallExpr *Call) {
878   PrintExpr(Call->getCallee());
879   OS << "(";
880   PrintCallArgs(Call);
881   OS << ")";
882 }
883 void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
884   // FIXME: Suppress printing implicit bases (like "this")
885   PrintExpr(Node->getBase());
886   if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
887     if (FD->isAnonymousStructOrUnion())
888       return;
889   OS << (Node->isArrow() ? "->" : ".");
890   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
891     Qualifier->print(OS, Policy);
892   if (Node->hasTemplateKeyword())
893     OS << "template ";
894   OS << Node->getMemberNameInfo();
895   if (Node->hasExplicitTemplateArgs())
896     OS << TemplateSpecializationType::PrintTemplateArgumentList(
897                                                     Node->getTemplateArgs(),
898                                                     Node->getNumTemplateArgs(),
899                                                                 Policy);
900 }
901 void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
902   PrintExpr(Node->getBase());
903   OS << (Node->isArrow() ? "->isa" : ".isa");
904 }
905 
906 void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
907   PrintExpr(Node->getBase());
908   OS << ".";
909   OS << Node->getAccessor().getName();
910 }
911 void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
912   OS << "(" << Node->getType().getAsString(Policy) << ")";
913   PrintExpr(Node->getSubExpr());
914 }
915 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
916   OS << "(" << Node->getType().getAsString(Policy) << ")";
917   PrintExpr(Node->getInitializer());
918 }
919 void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
920   // No need to print anything, simply forward to the sub expression.
921   PrintExpr(Node->getSubExpr());
922 }
923 void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
924   PrintExpr(Node->getLHS());
925   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
926   PrintExpr(Node->getRHS());
927 }
928 void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
929   PrintExpr(Node->getLHS());
930   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
931   PrintExpr(Node->getRHS());
932 }
933 void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
934   PrintExpr(Node->getCond());
935   OS << " ? ";
936   PrintExpr(Node->getLHS());
937   OS << " : ";
938   PrintExpr(Node->getRHS());
939 }
940 
941 // GNU extensions.
942 
943 void
944 StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
945   PrintExpr(Node->getCommon());
946   OS << " ?: ";
947   PrintExpr(Node->getFalseExpr());
948 }
949 void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
950   OS << "&&" << Node->getLabel()->getName();
951 }
952 
953 void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
954   OS << "(";
955   PrintRawCompoundStmt(E->getSubStmt());
956   OS << ")";
957 }
958 
959 void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
960   OS << "__builtin_choose_expr(";
961   PrintExpr(Node->getCond());
962   OS << ", ";
963   PrintExpr(Node->getLHS());
964   OS << ", ";
965   PrintExpr(Node->getRHS());
966   OS << ")";
967 }
968 
969 void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
970   OS << "__null";
971 }
972 
973 void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
974   OS << "__builtin_shufflevector(";
975   for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
976     if (i) OS << ", ";
977     PrintExpr(Node->getExpr(i));
978   }
979   OS << ")";
980 }
981 
982 void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
983   if (Node->getSyntacticForm()) {
984     Visit(Node->getSyntacticForm());
985     return;
986   }
987 
988   OS << "{ ";
989   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
990     if (i) OS << ", ";
991     if (Node->getInit(i))
992       PrintExpr(Node->getInit(i));
993     else
994       OS << "0";
995   }
996   OS << " }";
997 }
998 
999 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1000   OS << "( ";
1001   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1002     if (i) OS << ", ";
1003     PrintExpr(Node->getExpr(i));
1004   }
1005   OS << " )";
1006 }
1007 
1008 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1009   for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1010                       DEnd = Node->designators_end();
1011        D != DEnd; ++D) {
1012     if (D->isFieldDesignator()) {
1013       if (D->getDotLoc().isInvalid())
1014         OS << D->getFieldName()->getName() << ":";
1015       else
1016         OS << "." << D->getFieldName()->getName();
1017     } else {
1018       OS << "[";
1019       if (D->isArrayDesignator()) {
1020         PrintExpr(Node->getArrayIndex(*D));
1021       } else {
1022         PrintExpr(Node->getArrayRangeStart(*D));
1023         OS << " ... ";
1024         PrintExpr(Node->getArrayRangeEnd(*D));
1025       }
1026       OS << "]";
1027     }
1028   }
1029 
1030   OS << " = ";
1031   PrintExpr(Node->getInit());
1032 }
1033 
1034 void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1035   if (Policy.LangOpts.CPlusPlus)
1036     OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
1037   else {
1038     OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
1039     if (Node->getType()->isRecordType())
1040       OS << "{}";
1041     else
1042       OS << 0;
1043   }
1044 }
1045 
1046 void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1047   OS << "__builtin_va_arg(";
1048   PrintExpr(Node->getSubExpr());
1049   OS << ", ";
1050   OS << Node->getType().getAsString(Policy);
1051   OS << ")";
1052 }
1053 
1054 void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1055   PrintExpr(Node->getSyntacticForm());
1056 }
1057 
1058 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1059   const char *Name = 0;
1060   switch (Node->getOp()) {
1061     case AtomicExpr::Init:
1062       Name = "__atomic_init(";
1063       break;
1064     case AtomicExpr::Load:
1065       Name = "__atomic_load(";
1066       break;
1067     case AtomicExpr::Store:
1068       Name = "__atomic_store(";
1069       break;
1070     case AtomicExpr::CmpXchgStrong:
1071       Name = "__atomic_compare_exchange_strong(";
1072       break;
1073     case AtomicExpr::CmpXchgWeak:
1074       Name = "__atomic_compare_exchange_weak(";
1075       break;
1076     case AtomicExpr::Xchg:
1077       Name = "__atomic_exchange(";
1078       break;
1079     case AtomicExpr::Add:
1080       Name = "__atomic_fetch_add(";
1081       break;
1082     case AtomicExpr::Sub:
1083       Name = "__atomic_fetch_sub(";
1084       break;
1085     case AtomicExpr::And:
1086       Name = "__atomic_fetch_and(";
1087       break;
1088     case AtomicExpr::Or:
1089       Name = "__atomic_fetch_or(";
1090       break;
1091     case AtomicExpr::Xor:
1092       Name = "__atomic_fetch_xor(";
1093       break;
1094   }
1095   OS << Name;
1096   PrintExpr(Node->getPtr());
1097   OS << ", ";
1098   if (Node->getOp() != AtomicExpr::Load) {
1099     PrintExpr(Node->getVal1());
1100     OS << ", ";
1101   }
1102   if (Node->isCmpXChg()) {
1103     PrintExpr(Node->getVal2());
1104     OS << ", ";
1105   }
1106   if (Node->getOp() != AtomicExpr::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::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1217   OS << (Node->getValue() ? "true" : "false");
1218 }
1219 
1220 void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1221   OS << "nullptr";
1222 }
1223 
1224 void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1225   OS << "this";
1226 }
1227 
1228 void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1229   if (Node->getSubExpr() == 0)
1230     OS << "throw";
1231   else {
1232     OS << "throw ";
1233     PrintExpr(Node->getSubExpr());
1234   }
1235 }
1236 
1237 void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1238   // Nothing to print: we picked up the default argument
1239 }
1240 
1241 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1242   OS << Node->getType().getAsString(Policy);
1243   OS << "(";
1244   PrintExpr(Node->getSubExpr());
1245   OS << ")";
1246 }
1247 
1248 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1249   PrintExpr(Node->getSubExpr());
1250 }
1251 
1252 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1253   OS << Node->getType().getAsString(Policy);
1254   OS << "(";
1255   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1256                                          ArgEnd = Node->arg_end();
1257        Arg != ArgEnd; ++Arg) {
1258     if (Arg != Node->arg_begin())
1259       OS << ", ";
1260     PrintExpr(*Arg);
1261   }
1262   OS << ")";
1263 }
1264 
1265 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1266   if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1267     OS << TSInfo->getType().getAsString(Policy) << "()";
1268   else
1269     OS << Node->getType().getAsString(Policy) << "()";
1270 }
1271 
1272 void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1273   if (E->isGlobalNew())
1274     OS << "::";
1275   OS << "new ";
1276   unsigned NumPlace = E->getNumPlacementArgs();
1277   if (NumPlace > 0) {
1278     OS << "(";
1279     PrintExpr(E->getPlacementArg(0));
1280     for (unsigned i = 1; i < NumPlace; ++i) {
1281       OS << ", ";
1282       PrintExpr(E->getPlacementArg(i));
1283     }
1284     OS << ") ";
1285   }
1286   if (E->isParenTypeId())
1287     OS << "(";
1288   std::string TypeS;
1289   if (Expr *Size = E->getArraySize()) {
1290     llvm::raw_string_ostream s(TypeS);
1291     Size->printPretty(s, Context, Helper, Policy);
1292     s.flush();
1293     TypeS = "[" + TypeS + "]";
1294   }
1295   E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1296   OS << TypeS;
1297   if (E->isParenTypeId())
1298     OS << ")";
1299 
1300   if (E->hasInitializer()) {
1301     OS << "(";
1302     unsigned NumCons = E->getNumConstructorArgs();
1303     if (NumCons > 0) {
1304       PrintExpr(E->getConstructorArg(0));
1305       for (unsigned i = 1; i < NumCons; ++i) {
1306         OS << ", ";
1307         PrintExpr(E->getConstructorArg(i));
1308       }
1309     }
1310     OS << ")";
1311   }
1312 }
1313 
1314 void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1315   if (E->isGlobalDelete())
1316     OS << "::";
1317   OS << "delete ";
1318   if (E->isArrayForm())
1319     OS << "[] ";
1320   PrintExpr(E->getArgument());
1321 }
1322 
1323 void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1324   PrintExpr(E->getBase());
1325   if (E->isArrow())
1326     OS << "->";
1327   else
1328     OS << '.';
1329   if (E->getQualifier())
1330     E->getQualifier()->print(OS, Policy);
1331 
1332   std::string TypeS;
1333   if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1334     OS << II->getName();
1335   else
1336     E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1337   OS << TypeS;
1338 }
1339 
1340 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1341   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1342     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1343       // Don't print any defaulted arguments
1344       break;
1345     }
1346 
1347     if (i) OS << ", ";
1348     PrintExpr(E->getArg(i));
1349   }
1350 }
1351 
1352 void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1353   // Just forward to the sub expression.
1354   PrintExpr(E->getSubExpr());
1355 }
1356 
1357 void
1358 StmtPrinter::VisitCXXUnresolvedConstructExpr(
1359                                            CXXUnresolvedConstructExpr *Node) {
1360   OS << Node->getTypeAsWritten().getAsString(Policy);
1361   OS << "(";
1362   for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1363                                              ArgEnd = Node->arg_end();
1364        Arg != ArgEnd; ++Arg) {
1365     if (Arg != Node->arg_begin())
1366       OS << ", ";
1367     PrintExpr(*Arg);
1368   }
1369   OS << ")";
1370 }
1371 
1372 void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1373                                          CXXDependentScopeMemberExpr *Node) {
1374   if (!Node->isImplicitAccess()) {
1375     PrintExpr(Node->getBase());
1376     OS << (Node->isArrow() ? "->" : ".");
1377   }
1378   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1379     Qualifier->print(OS, Policy);
1380   if (Node->hasTemplateKeyword())
1381     OS << "template ";
1382   OS << Node->getMemberNameInfo();
1383   if (Node->hasExplicitTemplateArgs()) {
1384     OS << TemplateSpecializationType::PrintTemplateArgumentList(
1385                                                     Node->getTemplateArgs(),
1386                                                     Node->getNumTemplateArgs(),
1387                                                     Policy);
1388   }
1389 }
1390 
1391 void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1392   if (!Node->isImplicitAccess()) {
1393     PrintExpr(Node->getBase());
1394     OS << (Node->isArrow() ? "->" : ".");
1395   }
1396   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1397     Qualifier->print(OS, Policy);
1398   if (Node->hasTemplateKeyword())
1399     OS << "template ";
1400   OS << Node->getMemberNameInfo();
1401   if (Node->hasExplicitTemplateArgs()) {
1402     OS << TemplateSpecializationType::PrintTemplateArgumentList(
1403                                                     Node->getTemplateArgs(),
1404                                                     Node->getNumTemplateArgs(),
1405                                                     Policy);
1406   }
1407 }
1408 
1409 static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1410   switch (UTT) {
1411   case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1412   case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1413   case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1414   case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1415   case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1416   case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1417   case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1418   case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1419   case UTT_IsAbstract:            return "__is_abstract";
1420   case UTT_IsArithmetic:            return "__is_arithmetic";
1421   case UTT_IsArray:                 return "__is_array";
1422   case UTT_IsClass:               return "__is_class";
1423   case UTT_IsCompleteType:          return "__is_complete_type";
1424   case UTT_IsCompound:              return "__is_compound";
1425   case UTT_IsConst:                 return "__is_const";
1426   case UTT_IsEmpty:               return "__is_empty";
1427   case UTT_IsEnum:                return "__is_enum";
1428   case UTT_IsFinal:                 return "__is_final";
1429   case UTT_IsFloatingPoint:         return "__is_floating_point";
1430   case UTT_IsFunction:              return "__is_function";
1431   case UTT_IsFundamental:           return "__is_fundamental";
1432   case UTT_IsIntegral:              return "__is_integral";
1433   case UTT_IsLiteral:               return "__is_literal";
1434   case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1435   case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1436   case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1437   case UTT_IsMemberPointer:         return "__is_member_pointer";
1438   case UTT_IsObject:                return "__is_object";
1439   case UTT_IsPOD:                 return "__is_pod";
1440   case UTT_IsPointer:               return "__is_pointer";
1441   case UTT_IsPolymorphic:         return "__is_polymorphic";
1442   case UTT_IsReference:             return "__is_reference";
1443   case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1444   case UTT_IsScalar:                return "__is_scalar";
1445   case UTT_IsSigned:                return "__is_signed";
1446   case UTT_IsStandardLayout:        return "__is_standard_layout";
1447   case UTT_IsTrivial:               return "__is_trivial";
1448   case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1449   case UTT_IsUnion:               return "__is_union";
1450   case UTT_IsUnsigned:              return "__is_unsigned";
1451   case UTT_IsVoid:                  return "__is_void";
1452   case UTT_IsVolatile:              return "__is_volatile";
1453   }
1454   llvm_unreachable("Type trait not covered by switch statement");
1455 }
1456 
1457 static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1458   switch (BTT) {
1459   case BTT_IsBaseOf:         return "__is_base_of";
1460   case BTT_IsConvertible:    return "__is_convertible";
1461   case BTT_IsSame:           return "__is_same";
1462   case BTT_TypeCompatible:   return "__builtin_types_compatible_p";
1463   case BTT_IsConvertibleTo:  return "__is_convertible_to";
1464   }
1465   llvm_unreachable("Binary type trait not covered by switch");
1466 }
1467 
1468 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1469   switch (ATT) {
1470   case ATT_ArrayRank:        return "__array_rank";
1471   case ATT_ArrayExtent:      return "__array_extent";
1472   }
1473   llvm_unreachable("Array type trait not covered by switch");
1474 }
1475 
1476 static const char *getExpressionTraitName(ExpressionTrait ET) {
1477   switch (ET) {
1478   case ET_IsLValueExpr:      return "__is_lvalue_expr";
1479   case ET_IsRValueExpr:      return "__is_rvalue_expr";
1480   }
1481   llvm_unreachable("Expression type trait not covered by switch");
1482 }
1483 
1484 void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1485   OS << getTypeTraitName(E->getTrait()) << "("
1486      << E->getQueriedType().getAsString(Policy) << ")";
1487 }
1488 
1489 void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1490   OS << getTypeTraitName(E->getTrait()) << "("
1491      << E->getLhsType().getAsString(Policy) << ","
1492      << E->getRhsType().getAsString(Policy) << ")";
1493 }
1494 
1495 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1496   OS << getTypeTraitName(E->getTrait()) << "("
1497      << E->getQueriedType().getAsString(Policy) << ")";
1498 }
1499 
1500 void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1501     OS << getExpressionTraitName(E->getTrait()) << "(";
1502     PrintExpr(E->getQueriedExpression());
1503     OS << ")";
1504 }
1505 
1506 void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1507   OS << "noexcept(";
1508   PrintExpr(E->getOperand());
1509   OS << ")";
1510 }
1511 
1512 void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1513   PrintExpr(E->getPattern());
1514   OS << "...";
1515 }
1516 
1517 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1518   OS << "sizeof...(" << E->getPack()->getNameAsString() << ")";
1519 }
1520 
1521 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1522                                        SubstNonTypeTemplateParmPackExpr *Node) {
1523   OS << Node->getParameterPack()->getNameAsString();
1524 }
1525 
1526 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1527                                        SubstNonTypeTemplateParmExpr *Node) {
1528   Visit(Node->getReplacement());
1529 }
1530 
1531 void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1532   PrintExpr(Node->GetTemporaryExpr());
1533 }
1534 
1535 // Obj-C
1536 
1537 void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1538   OS << "@";
1539   VisitStringLiteral(Node->getString());
1540 }
1541 
1542 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1543   OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1544 }
1545 
1546 void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1547   OS << "@selector(" << Node->getSelector().getAsString() << ')';
1548 }
1549 
1550 void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1551   OS << "@protocol(" << *Node->getProtocol() << ')';
1552 }
1553 
1554 void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1555   OS << "[";
1556   switch (Mess->getReceiverKind()) {
1557   case ObjCMessageExpr::Instance:
1558     PrintExpr(Mess->getInstanceReceiver());
1559     break;
1560 
1561   case ObjCMessageExpr::Class:
1562     OS << Mess->getClassReceiver().getAsString(Policy);
1563     break;
1564 
1565   case ObjCMessageExpr::SuperInstance:
1566   case ObjCMessageExpr::SuperClass:
1567     OS << "Super";
1568     break;
1569   }
1570 
1571   OS << ' ';
1572   Selector selector = Mess->getSelector();
1573   if (selector.isUnarySelector()) {
1574     OS << selector.getNameForSlot(0);
1575   } else {
1576     for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1577       if (i < selector.getNumArgs()) {
1578         if (i > 0) OS << ' ';
1579         if (selector.getIdentifierInfoForSlot(i))
1580           OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1581         else
1582            OS << ":";
1583       }
1584       else OS << ", "; // Handle variadic methods.
1585 
1586       PrintExpr(Mess->getArg(i));
1587     }
1588   }
1589   OS << "]";
1590 }
1591 
1592 void
1593 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1594   PrintExpr(E->getSubExpr());
1595 }
1596 
1597 void
1598 StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1599   OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1600      << ")";
1601   PrintExpr(E->getSubExpr());
1602 }
1603 
1604 void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1605   BlockDecl *BD = Node->getBlockDecl();
1606   OS << "^";
1607 
1608   const FunctionType *AFT = Node->getFunctionType();
1609 
1610   if (isa<FunctionNoProtoType>(AFT)) {
1611     OS << "()";
1612   } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1613     OS << '(';
1614     std::string ParamStr;
1615     for (BlockDecl::param_iterator AI = BD->param_begin(),
1616          E = BD->param_end(); AI != E; ++AI) {
1617       if (AI != BD->param_begin()) OS << ", ";
1618       ParamStr = (*AI)->getNameAsString();
1619       (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1620       OS << ParamStr;
1621     }
1622 
1623     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1624     if (FT->isVariadic()) {
1625       if (!BD->param_empty()) OS << ", ";
1626       OS << "...";
1627     }
1628     OS << ')';
1629   }
1630 }
1631 
1632 void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
1633   OS << *Node->getDecl();
1634 }
1635 
1636 void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
1637   PrintExpr(Node->getSourceExpr());
1638 }
1639 
1640 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1641   OS << "__builtin_astype(";
1642   PrintExpr(Node->getSrcExpr());
1643   OS << ", " << Node->getType().getAsString();
1644   OS << ")";
1645 }
1646 
1647 //===----------------------------------------------------------------------===//
1648 // Stmt method implementations
1649 //===----------------------------------------------------------------------===//
1650 
1651 void Stmt::dumpPretty(ASTContext& Context) const {
1652   printPretty(llvm::errs(), Context, 0,
1653               PrintingPolicy(Context.getLangOptions()));
1654 }
1655 
1656 void Stmt::printPretty(raw_ostream &OS, ASTContext& Context,
1657                        PrinterHelper* Helper,
1658                        const PrintingPolicy &Policy,
1659                        unsigned Indentation) const {
1660   if (this == 0) {
1661     OS << "<NULL>";
1662     return;
1663   }
1664 
1665   if (Policy.Dump && &Context) {
1666     dump(OS, Context.getSourceManager());
1667     return;
1668   }
1669 
1670   StmtPrinter P(OS, Context, Helper, Policy, Indentation);
1671   P.Visit(const_cast<Stmt*>(this));
1672 }
1673 
1674 //===----------------------------------------------------------------------===//
1675 // PrinterHelper
1676 //===----------------------------------------------------------------------===//
1677 
1678 // Implement virtual destructor.
1679 PrinterHelper::~PrinterHelper() {}
1680