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