Put Target definitions inside Target specific header, and llvm namespace.
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
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 writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Config/config.h"
35 #include <algorithm>
36 #include <set>
37
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
42          cl::value_desc("function name"));
43
44 enum WhatToGenerate {
45   GenProgram,
46   GenModule,
47   GenContents,
48   GenFunction,
49   GenFunctions,
50   GenInline,
51   GenVariable,
52   GenType
53 };
54
55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
56   cl::desc("Choose what kind of output to generate"),
57   cl::init(GenProgram),
58   cl::values(
59     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
60     clEnumValN(GenModule,   "module",    "Generate a module definition"),
61     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
62     clEnumValN(GenFunction, "function",  "Generate a function definition"),
63     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
65     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
66     clEnumValN(GenType,     "type",      "Generate a type definition"),
67     clEnumValEnd
68   )
69 );
70
71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
72   cl::desc("Specify the name of the thing to generate"),
73   cl::init("!bad!"));
74
75 // Register the target.
76 static RegisterTarget<CPPTargetMachine> X(TheCppBackendTarget, "cpp", "C++ backend");
77
78 // Force static initialization.
79 extern "C" void LLVMInitializeCppBackendTarget() { }
80
81 namespace {
82   typedef std::vector<const Type*> TypeList;
83   typedef std::map<const Type*,std::string> TypeMap;
84   typedef std::map<const Value*,std::string> ValueMap;
85   typedef std::set<std::string> NameSet;
86   typedef std::set<const Type*> TypeSet;
87   typedef std::set<const Value*> ValueSet;
88   typedef std::map<const Value*,std::string> ForwardRefMap;
89
90   /// CppWriter - This class is the main chunk of code that converts an LLVM
91   /// module to a C++ translation unit.
92   class CppWriter : public ModulePass {
93     formatted_raw_ostream &Out;
94     const Module *TheModule;
95     uint64_t uniqueNum;
96     TypeMap TypeNames;
97     ValueMap ValueNames;
98     TypeMap UnresolvedTypes;
99     TypeList TypeStack;
100     NameSet UsedNames;
101     TypeSet DefinedTypes;
102     ValueSet DefinedValues;
103     ForwardRefMap ForwardRefs;
104     bool is_inline;
105
106   public:
107     static char ID;
108     explicit CppWriter(formatted_raw_ostream &o) :
109       ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
110
111     virtual const char *getPassName() const { return "C++ backend"; }
112
113     bool runOnModule(Module &M);
114
115     void printProgram(const std::string& fname, const std::string& modName );
116     void printModule(const std::string& fname, const std::string& modName );
117     void printContents(const std::string& fname, const std::string& modName );
118     void printFunction(const std::string& fname, const std::string& funcName );
119     void printFunctions();
120     void printInline(const std::string& fname, const std::string& funcName );
121     void printVariable(const std::string& fname, const std::string& varName );
122     void printType(const std::string& fname, const std::string& typeName );
123
124     void error(const std::string& msg);
125
126   private:
127     void printLinkageType(GlobalValue::LinkageTypes LT);
128     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
129     void printCallingConv(unsigned cc);
130     void printEscapedString(const std::string& str);
131     void printCFP(const ConstantFP* CFP);
132
133     std::string getCppName(const Type* val);
134     inline void printCppName(const Type* val);
135
136     std::string getCppName(const Value* val);
137     inline void printCppName(const Value* val);
138
139     void printAttributes(const AttrListPtr &PAL, const std::string &name);
140     bool printTypeInternal(const Type* Ty);
141     inline void printType(const Type* Ty);
142     void printTypes(const Module* M);
143
144     void printConstant(const Constant *CPV);
145     void printConstants(const Module* M);
146
147     void printVariableUses(const GlobalVariable *GV);
148     void printVariableHead(const GlobalVariable *GV);
149     void printVariableBody(const GlobalVariable *GV);
150
151     void printFunctionUses(const Function *F);
152     void printFunctionHead(const Function *F);
153     void printFunctionBody(const Function *F);
154     void printInstruction(const Instruction *I, const std::string& bbname);
155     std::string getOpName(Value*);
156
157     void printModuleBody();
158   };
159
160   static unsigned indent_level = 0;
161   inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
162     Out << "\n";
163     if (delta >= 0 || indent_level >= unsigned(-delta))
164       indent_level += delta;
165     for (unsigned i = 0; i < indent_level; ++i)
166       Out << "  ";
167     return Out;
168   }
169
170   inline void in() { indent_level++; }
171   inline void out() { if (indent_level >0) indent_level--; }
172
173   inline void
174   sanitize(std::string& str) {
175     for (size_t i = 0; i < str.length(); ++i)
176       if (!isalnum(str[i]) && str[i] != '_')
177         str[i] = '_';
178   }
179
180   inline std::string
181   getTypePrefix(const Type* Ty ) {
182     switch (Ty->getTypeID()) {
183     case Type::VoidTyID:     return "void_";
184     case Type::IntegerTyID:
185       return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
186         "_";
187     case Type::FloatTyID:    return "float_";
188     case Type::DoubleTyID:   return "double_";
189     case Type::LabelTyID:    return "label_";
190     case Type::FunctionTyID: return "func_";
191     case Type::StructTyID:   return "struct_";
192     case Type::ArrayTyID:    return "array_";
193     case Type::PointerTyID:  return "ptr_";
194     case Type::VectorTyID:   return "packed_";
195     case Type::OpaqueTyID:   return "opaque_";
196     default:                 return "other_";
197     }
198     return "unknown_";
199   }
200
201   // Looks up the type in the symbol table and returns a pointer to its name or
202   // a null pointer if it wasn't found. Note that this isn't the same as the
203   // Mode::getTypeName function which will return an empty string, not a null
204   // pointer if the name is not found.
205   inline const std::string*
206   findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
207     TypeSymbolTable::const_iterator TI = ST.begin();
208     TypeSymbolTable::const_iterator TE = ST.end();
209     for (;TI != TE; ++TI)
210       if (TI->second == Ty)
211         return &(TI->first);
212     return 0;
213   }
214
215   void CppWriter::error(const std::string& msg) {
216     llvm_report_error(msg);
217   }
218
219   // printCFP - Print a floating point constant .. very carefully :)
220   // This makes sure that conversion to/from floating yields the same binary
221   // result so that we don't lose precision.
222   void CppWriter::printCFP(const ConstantFP *CFP) {
223     bool ignored;
224     APFloat APF = APFloat(CFP->getValueAPF());  // copy
225     if (CFP->getType() == Type::FloatTy)
226       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
227     Out << "ConstantFP::get(";
228     Out << "APFloat(";
229 #if HAVE_PRINTF_A
230     char Buffer[100];
231     sprintf(Buffer, "%A", APF.convertToDouble());
232     if ((!strncmp(Buffer, "0x", 2) ||
233          !strncmp(Buffer, "-0x", 3) ||
234          !strncmp(Buffer, "+0x", 3)) &&
235         APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
236       if (CFP->getType() == Type::DoubleTy)
237         Out << "BitsToDouble(" << Buffer << ")";
238       else
239         Out << "BitsToFloat((float)" << Buffer << ")";
240       Out << ")";
241     } else {
242 #endif
243       std::string StrVal = ftostr(CFP->getValueAPF());
244
245       while (StrVal[0] == ' ')
246         StrVal.erase(StrVal.begin());
247
248       // Check to make sure that the stringized number is not some string like
249       // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
250       if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
251            ((StrVal[0] == '-' || StrVal[0] == '+') &&
252             (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
253           (CFP->isExactlyValue(atof(StrVal.c_str())))) {
254         if (CFP->getType() == Type::DoubleTy)
255           Out <<  StrVal;
256         else
257           Out << StrVal << "f";
258       } else if (CFP->getType() == Type::DoubleTy)
259         Out << "BitsToDouble(0x"
260             << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
261             << "ULL) /* " << StrVal << " */";
262       else
263         Out << "BitsToFloat(0x"
264             << utohexstr((uint32_t)CFP->getValueAPF().
265                                         bitcastToAPInt().getZExtValue())
266             << "U) /* " << StrVal << " */";
267       Out << ")";
268 #if HAVE_PRINTF_A
269     }
270 #endif
271     Out << ")";
272   }
273
274   void CppWriter::printCallingConv(unsigned cc){
275     // Print the calling convention.
276     switch (cc) {
277     case CallingConv::C:     Out << "CallingConv::C"; break;
278     case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
279     case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
280     case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
281     default:                 Out << cc; break;
282     }
283   }
284
285   void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
286     switch (LT) {
287     case GlobalValue::InternalLinkage:
288       Out << "GlobalValue::InternalLinkage"; break;
289     case GlobalValue::PrivateLinkage:
290       Out << "GlobalValue::PrivateLinkage"; break;
291     case GlobalValue::AvailableExternallyLinkage:
292       Out << "GlobalValue::AvailableExternallyLinkage "; break;
293     case GlobalValue::LinkOnceAnyLinkage:
294       Out << "GlobalValue::LinkOnceAnyLinkage "; break;
295     case GlobalValue::LinkOnceODRLinkage:
296       Out << "GlobalValue::LinkOnceODRLinkage "; break;
297     case GlobalValue::WeakAnyLinkage:
298       Out << "GlobalValue::WeakAnyLinkage"; break;
299     case GlobalValue::WeakODRLinkage:
300       Out << "GlobalValue::WeakODRLinkage"; break;
301     case GlobalValue::AppendingLinkage:
302       Out << "GlobalValue::AppendingLinkage"; break;
303     case GlobalValue::ExternalLinkage:
304       Out << "GlobalValue::ExternalLinkage"; break;
305     case GlobalValue::DLLImportLinkage:
306       Out << "GlobalValue::DLLImportLinkage"; break;
307     case GlobalValue::DLLExportLinkage:
308       Out << "GlobalValue::DLLExportLinkage"; break;
309     case GlobalValue::ExternalWeakLinkage:
310       Out << "GlobalValue::ExternalWeakLinkage"; break;
311     case GlobalValue::GhostLinkage:
312       Out << "GlobalValue::GhostLinkage"; break;
313     case GlobalValue::CommonLinkage:
314       Out << "GlobalValue::CommonLinkage"; break;
315     }
316   }
317
318   void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
319     switch (VisType) {
320     default: llvm_unreachable("Unknown GVar visibility");
321     case GlobalValue::DefaultVisibility:
322       Out << "GlobalValue::DefaultVisibility";
323       break;
324     case GlobalValue::HiddenVisibility:
325       Out << "GlobalValue::HiddenVisibility";
326       break;
327     case GlobalValue::ProtectedVisibility:
328       Out << "GlobalValue::ProtectedVisibility";
329       break;
330     }
331   }
332
333   // printEscapedString - Print each character of the specified string, escaping
334   // it if it is not printable or if it is an escape char.
335   void CppWriter::printEscapedString(const std::string &Str) {
336     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
337       unsigned char C = Str[i];
338       if (isprint(C) && C != '"' && C != '\\') {
339         Out << C;
340       } else {
341         Out << "\\x"
342             << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
343             << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
344       }
345     }
346   }
347
348   std::string CppWriter::getCppName(const Type* Ty) {
349     // First, handle the primitive types .. easy
350     if (Ty->isPrimitiveType() || Ty->isInteger()) {
351       switch (Ty->getTypeID()) {
352       case Type::VoidTyID:   return "Type::VoidTy";
353       case Type::IntegerTyID: {
354         unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
355         return "IntegerType::get(" + utostr(BitWidth) + ")";
356       }
357       case Type::X86_FP80TyID: return "Type::X86_FP80Ty";
358       case Type::FloatTyID:    return "Type::FloatTy";
359       case Type::DoubleTyID:   return "Type::DoubleTy";
360       case Type::LabelTyID:    return "Type::LabelTy";
361       default:
362         error("Invalid primitive type");
363         break;
364       }
365       return "Type::VoidTy"; // shouldn't be returned, but make it sensible
366     }
367
368     // Now, see if we've seen the type before and return that
369     TypeMap::iterator I = TypeNames.find(Ty);
370     if (I != TypeNames.end())
371       return I->second;
372
373     // Okay, let's build a new name for this type. Start with a prefix
374     const char* prefix = 0;
375     switch (Ty->getTypeID()) {
376     case Type::FunctionTyID:    prefix = "FuncTy_"; break;
377     case Type::StructTyID:      prefix = "StructTy_"; break;
378     case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
379     case Type::PointerTyID:     prefix = "PointerTy_"; break;
380     case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
381     case Type::VectorTyID:      prefix = "VectorTy_"; break;
382     default:                    prefix = "OtherTy_"; break; // prevent breakage
383     }
384
385     // See if the type has a name in the symboltable and build accordingly
386     const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
387     std::string name;
388     if (tName)
389       name = std::string(prefix) + *tName;
390     else
391       name = std::string(prefix) + utostr(uniqueNum++);
392     sanitize(name);
393
394     // Save the name
395     return TypeNames[Ty] = name;
396   }
397
398   void CppWriter::printCppName(const Type* Ty) {
399     printEscapedString(getCppName(Ty));
400   }
401
402   std::string CppWriter::getCppName(const Value* val) {
403     std::string name;
404     ValueMap::iterator I = ValueNames.find(val);
405     if (I != ValueNames.end() && I->first == val)
406       return  I->second;
407
408     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
409       name = std::string("gvar_") +
410         getTypePrefix(GV->getType()->getElementType());
411     } else if (isa<Function>(val)) {
412       name = std::string("func_");
413     } else if (const Constant* C = dyn_cast<Constant>(val)) {
414       name = std::string("const_") + getTypePrefix(C->getType());
415     } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
416       if (is_inline) {
417         unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
418                                         Function::const_arg_iterator(Arg)) + 1;
419         name = std::string("arg_") + utostr(argNum);
420         NameSet::iterator NI = UsedNames.find(name);
421         if (NI != UsedNames.end())
422           name += std::string("_") + utostr(uniqueNum++);
423         UsedNames.insert(name);
424         return ValueNames[val] = name;
425       } else {
426         name = getTypePrefix(val->getType());
427       }
428     } else {
429       name = getTypePrefix(val->getType());
430     }
431     name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
432     sanitize(name);
433     NameSet::iterator NI = UsedNames.find(name);
434     if (NI != UsedNames.end())
435       name += std::string("_") + utostr(uniqueNum++);
436     UsedNames.insert(name);
437     return ValueNames[val] = name;
438   }
439
440   void CppWriter::printCppName(const Value* val) {
441     printEscapedString(getCppName(val));
442   }
443
444   void CppWriter::printAttributes(const AttrListPtr &PAL,
445                                   const std::string &name) {
446     Out << "AttrListPtr " << name << "_PAL;";
447     nl(Out);
448     if (!PAL.isEmpty()) {
449       Out << '{'; in(); nl(Out);
450       Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
451       Out << "AttributeWithIndex PAWI;"; nl(Out);
452       for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
453         unsigned index = PAL.getSlot(i).Index;
454         Attributes attrs = PAL.getSlot(i).Attrs;
455         Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
456 #define HANDLE_ATTR(X)                 \
457         if (attrs & Attribute::X)      \
458           Out << " | Attribute::" #X;  \
459         attrs &= ~Attribute::X;
460         
461         HANDLE_ATTR(SExt);
462         HANDLE_ATTR(ZExt);
463         HANDLE_ATTR(NoReturn);
464         HANDLE_ATTR(InReg);
465         HANDLE_ATTR(StructRet);
466         HANDLE_ATTR(NoUnwind);
467         HANDLE_ATTR(NoAlias);
468         HANDLE_ATTR(ByVal);
469         HANDLE_ATTR(Nest);
470         HANDLE_ATTR(ReadNone);
471         HANDLE_ATTR(ReadOnly);
472         HANDLE_ATTR(NoInline);
473         HANDLE_ATTR(AlwaysInline);
474         HANDLE_ATTR(OptimizeForSize);
475         HANDLE_ATTR(StackProtect);
476         HANDLE_ATTR(StackProtectReq);
477         HANDLE_ATTR(NoCapture);
478 #undef HANDLE_ATTR
479         assert(attrs == 0 && "Unhandled attribute!");
480         Out << ";";
481         nl(Out);
482         Out << "Attrs.push_back(PAWI);";
483         nl(Out);
484       }
485       Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
486       nl(Out);
487       out(); nl(Out);
488       Out << '}'; nl(Out);
489     }
490   }
491
492   bool CppWriter::printTypeInternal(const Type* Ty) {
493     // We don't print definitions for primitive types
494     if (Ty->isPrimitiveType() || Ty->isInteger())
495       return false;
496
497     // If we already defined this type, we don't need to define it again.
498     if (DefinedTypes.find(Ty) != DefinedTypes.end())
499       return false;
500
501     // Everything below needs the name for the type so get it now.
502     std::string typeName(getCppName(Ty));
503
504     // Search the type stack for recursion. If we find it, then generate this
505     // as an OpaqueType, but make sure not to do this multiple times because
506     // the type could appear in multiple places on the stack. Once the opaque
507     // definition is issued, it must not be re-issued. Consequently we have to
508     // check the UnresolvedTypes list as well.
509     TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
510                                             Ty);
511     if (TI != TypeStack.end()) {
512       TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
513       if (I == UnresolvedTypes.end()) {
514         Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
515         nl(Out);
516         UnresolvedTypes[Ty] = typeName;
517       }
518       return true;
519     }
520
521     // We're going to print a derived type which, by definition, contains other
522     // types. So, push this one we're printing onto the type stack to assist with
523     // recursive definitions.
524     TypeStack.push_back(Ty);
525
526     // Print the type definition
527     switch (Ty->getTypeID()) {
528     case Type::FunctionTyID:  {
529       const FunctionType* FT = cast<FunctionType>(Ty);
530       Out << "std::vector<const Type*>" << typeName << "_args;";
531       nl(Out);
532       FunctionType::param_iterator PI = FT->param_begin();
533       FunctionType::param_iterator PE = FT->param_end();
534       for (; PI != PE; ++PI) {
535         const Type* argTy = static_cast<const Type*>(*PI);
536         bool isForward = printTypeInternal(argTy);
537         std::string argName(getCppName(argTy));
538         Out << typeName << "_args.push_back(" << argName;
539         if (isForward)
540           Out << "_fwd";
541         Out << ");";
542         nl(Out);
543       }
544       bool isForward = printTypeInternal(FT->getReturnType());
545       std::string retTypeName(getCppName(FT->getReturnType()));
546       Out << "FunctionType* " << typeName << " = FunctionType::get(";
547       in(); nl(Out) << "/*Result=*/" << retTypeName;
548       if (isForward)
549         Out << "_fwd";
550       Out << ",";
551       nl(Out) << "/*Params=*/" << typeName << "_args,";
552       nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
553       out();
554       nl(Out);
555       break;
556     }
557     case Type::StructTyID: {
558       const StructType* ST = cast<StructType>(Ty);
559       Out << "std::vector<const Type*>" << typeName << "_fields;";
560       nl(Out);
561       StructType::element_iterator EI = ST->element_begin();
562       StructType::element_iterator EE = ST->element_end();
563       for (; EI != EE; ++EI) {
564         const Type* fieldTy = static_cast<const Type*>(*EI);
565         bool isForward = printTypeInternal(fieldTy);
566         std::string fieldName(getCppName(fieldTy));
567         Out << typeName << "_fields.push_back(" << fieldName;
568         if (isForward)
569           Out << "_fwd";
570         Out << ");";
571         nl(Out);
572       }
573       Out << "StructType* " << typeName << " = StructType::get("
574           << typeName << "_fields, /*isPacked=*/"
575           << (ST->isPacked() ? "true" : "false") << ");";
576       nl(Out);
577       break;
578     }
579     case Type::ArrayTyID: {
580       const ArrayType* AT = cast<ArrayType>(Ty);
581       const Type* ET = AT->getElementType();
582       bool isForward = printTypeInternal(ET);
583       std::string elemName(getCppName(ET));
584       Out << "ArrayType* " << typeName << " = ArrayType::get("
585           << elemName << (isForward ? "_fwd" : "")
586           << ", " << utostr(AT->getNumElements()) << ");";
587       nl(Out);
588       break;
589     }
590     case Type::PointerTyID: {
591       const PointerType* PT = cast<PointerType>(Ty);
592       const Type* ET = PT->getElementType();
593       bool isForward = printTypeInternal(ET);
594       std::string elemName(getCppName(ET));
595       Out << "PointerType* " << typeName << " = PointerType::get("
596           << elemName << (isForward ? "_fwd" : "")
597           << ", " << utostr(PT->getAddressSpace()) << ");";
598       nl(Out);
599       break;
600     }
601     case Type::VectorTyID: {
602       const VectorType* PT = cast<VectorType>(Ty);
603       const Type* ET = PT->getElementType();
604       bool isForward = printTypeInternal(ET);
605       std::string elemName(getCppName(ET));
606       Out << "VectorType* " << typeName << " = VectorType::get("
607           << elemName << (isForward ? "_fwd" : "")
608           << ", " << utostr(PT->getNumElements()) << ");";
609       nl(Out);
610       break;
611     }
612     case Type::OpaqueTyID: {
613       Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
614       nl(Out);
615       break;
616     }
617     default:
618       error("Invalid TypeID");
619     }
620
621     // If the type had a name, make sure we recreate it.
622     const std::string* progTypeName =
623       findTypeName(TheModule->getTypeSymbolTable(),Ty);
624     if (progTypeName) {
625       Out << "mod->addTypeName(\"" << *progTypeName << "\", "
626           << typeName << ");";
627       nl(Out);
628     }
629
630     // Pop us off the type stack
631     TypeStack.pop_back();
632
633     // Indicate that this type is now defined.
634     DefinedTypes.insert(Ty);
635
636     // Early resolve as many unresolved types as possible. Search the unresolved
637     // types map for the type we just printed. Now that its definition is complete
638     // we can resolve any previous references to it. This prevents a cascade of
639     // unresolved types.
640     TypeMap::iterator I = UnresolvedTypes.find(Ty);
641     if (I != UnresolvedTypes.end()) {
642       Out << "cast<OpaqueType>(" << I->second
643           << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
644       nl(Out);
645       Out << I->second << " = cast<";
646       switch (Ty->getTypeID()) {
647       case Type::FunctionTyID: Out << "FunctionType"; break;
648       case Type::ArrayTyID:    Out << "ArrayType"; break;
649       case Type::StructTyID:   Out << "StructType"; break;
650       case Type::VectorTyID:   Out << "VectorType"; break;
651       case Type::PointerTyID:  Out << "PointerType"; break;
652       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
653       default:                 Out << "NoSuchDerivedType"; break;
654       }
655       Out << ">(" << I->second << "_fwd.get());";
656       nl(Out); nl(Out);
657       UnresolvedTypes.erase(I);
658     }
659
660     // Finally, separate the type definition from other with a newline.
661     nl(Out);
662
663     // We weren't a recursive type
664     return false;
665   }
666
667   // Prints a type definition. Returns true if it could not resolve all the
668   // types in the definition but had to use a forward reference.
669   void CppWriter::printType(const Type* Ty) {
670     assert(TypeStack.empty());
671     TypeStack.clear();
672     printTypeInternal(Ty);
673     assert(TypeStack.empty());
674   }
675
676   void CppWriter::printTypes(const Module* M) {
677     // Walk the symbol table and print out all its types
678     const TypeSymbolTable& symtab = M->getTypeSymbolTable();
679     for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
680          TI != TE; ++TI) {
681
682       // For primitive types and types already defined, just add a name
683       TypeMap::const_iterator TNI = TypeNames.find(TI->second);
684       if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
685           TNI != TypeNames.end()) {
686         Out << "mod->addTypeName(\"";
687         printEscapedString(TI->first);
688         Out << "\", " << getCppName(TI->second) << ");";
689         nl(Out);
690         // For everything else, define the type
691       } else {
692         printType(TI->second);
693       }
694     }
695
696     // Add all of the global variables to the value table...
697     for (Module::const_global_iterator I = TheModule->global_begin(),
698            E = TheModule->global_end(); I != E; ++I) {
699       if (I->hasInitializer())
700         printType(I->getInitializer()->getType());
701       printType(I->getType());
702     }
703
704     // Add all the functions to the table
705     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
706          FI != FE; ++FI) {
707       printType(FI->getReturnType());
708       printType(FI->getFunctionType());
709       // Add all the function arguments
710       for (Function::const_arg_iterator AI = FI->arg_begin(),
711              AE = FI->arg_end(); AI != AE; ++AI) {
712         printType(AI->getType());
713       }
714
715       // Add all of the basic blocks and instructions
716       for (Function::const_iterator BB = FI->begin(),
717              E = FI->end(); BB != E; ++BB) {
718         printType(BB->getType());
719         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
720              ++I) {
721           printType(I->getType());
722           for (unsigned i = 0; i < I->getNumOperands(); ++i)
723             printType(I->getOperand(i)->getType());
724         }
725       }
726     }
727   }
728
729
730   // printConstant - Print out a constant pool entry...
731   void CppWriter::printConstant(const Constant *CV) {
732     // First, if the constant is actually a GlobalValue (variable or function)
733     // or its already in the constant list then we've printed it already and we
734     // can just return.
735     if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
736       return;
737
738     std::string constName(getCppName(CV));
739     std::string typeName(getCppName(CV->getType()));
740
741     if (isa<GlobalValue>(CV)) {
742       // Skip variables and functions, we emit them elsewhere
743       return;
744     }
745
746     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
747       std::string constValue = CI->getValue().toString(10, true);
748       Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
749           << cast<IntegerType>(CI->getType())->getBitWidth() << ",  \""
750           <<  constValue << "\", " << constValue.length() << ", 10));";
751     } else if (isa<ConstantAggregateZero>(CV)) {
752       Out << "ConstantAggregateZero* " << constName
753           << " = ConstantAggregateZero::get(" << typeName << ");";
754     } else if (isa<ConstantPointerNull>(CV)) {
755       Out << "ConstantPointerNull* " << constName
756           << " = ConstantPointerNull::get(" << typeName << ");";
757     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
758       Out << "ConstantFP* " << constName << " = ";
759       printCFP(CFP);
760       Out << ";";
761     } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
762       if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
763         Out << "Constant* " << constName << " = ConstantArray::get(\"";
764         std::string tmp = CA->getAsString();
765         bool nullTerminate = false;
766         if (tmp[tmp.length()-1] == 0) {
767           tmp.erase(tmp.length()-1);
768           nullTerminate = true;
769         }
770         printEscapedString(tmp);
771         // Determine if we want null termination or not.
772         if (nullTerminate)
773           Out << "\", true"; // Indicate that the null terminator should be
774                              // added.
775         else
776           Out << "\", false";// No null terminator
777         Out << ");";
778       } else {
779         Out << "std::vector<Constant*> " << constName << "_elems;";
780         nl(Out);
781         unsigned N = CA->getNumOperands();
782         for (unsigned i = 0; i < N; ++i) {
783           printConstant(CA->getOperand(i)); // recurse to print operands
784           Out << constName << "_elems.push_back("
785               << getCppName(CA->getOperand(i)) << ");";
786           nl(Out);
787         }
788         Out << "Constant* " << constName << " = ConstantArray::get("
789             << typeName << ", " << constName << "_elems);";
790       }
791     } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
792       Out << "std::vector<Constant*> " << constName << "_fields;";
793       nl(Out);
794       unsigned N = CS->getNumOperands();
795       for (unsigned i = 0; i < N; i++) {
796         printConstant(CS->getOperand(i));
797         Out << constName << "_fields.push_back("
798             << getCppName(CS->getOperand(i)) << ");";
799         nl(Out);
800       }
801       Out << "Constant* " << constName << " = ConstantStruct::get("
802           << typeName << ", " << constName << "_fields);";
803     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
804       Out << "std::vector<Constant*> " << constName << "_elems;";
805       nl(Out);
806       unsigned N = CP->getNumOperands();
807       for (unsigned i = 0; i < N; ++i) {
808         printConstant(CP->getOperand(i));
809         Out << constName << "_elems.push_back("
810             << getCppName(CP->getOperand(i)) << ");";
811         nl(Out);
812       }
813       Out << "Constant* " << constName << " = ConstantVector::get("
814           << typeName << ", " << constName << "_elems);";
815     } else if (isa<UndefValue>(CV)) {
816       Out << "UndefValue* " << constName << " = UndefValue::get("
817           << typeName << ");";
818     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
819       if (CE->getOpcode() == Instruction::GetElementPtr) {
820         Out << "std::vector<Constant*> " << constName << "_indices;";
821         nl(Out);
822         printConstant(CE->getOperand(0));
823         for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
824           printConstant(CE->getOperand(i));
825           Out << constName << "_indices.push_back("
826               << getCppName(CE->getOperand(i)) << ");";
827           nl(Out);
828         }
829         Out << "Constant* " << constName
830             << " = ConstantExpr::getGetElementPtr("
831             << getCppName(CE->getOperand(0)) << ", "
832             << "&" << constName << "_indices[0], "
833             << constName << "_indices.size()"
834             << " );";
835       } else if (CE->isCast()) {
836         printConstant(CE->getOperand(0));
837         Out << "Constant* " << constName << " = ConstantExpr::getCast(";
838         switch (CE->getOpcode()) {
839         default: llvm_unreachable("Invalid cast opcode");
840         case Instruction::Trunc: Out << "Instruction::Trunc"; break;
841         case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
842         case Instruction::SExt:  Out << "Instruction::SExt"; break;
843         case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
844         case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
845         case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
846         case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
847         case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
848         case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
849         case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
850         case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
851         case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
852         }
853         Out << ", " << getCppName(CE->getOperand(0)) << ", "
854             << getCppName(CE->getType()) << ");";
855       } else {
856         unsigned N = CE->getNumOperands();
857         for (unsigned i = 0; i < N; ++i ) {
858           printConstant(CE->getOperand(i));
859         }
860         Out << "Constant* " << constName << " = ConstantExpr::";
861         switch (CE->getOpcode()) {
862         case Instruction::Add:    Out << "getAdd(";  break;
863         case Instruction::FAdd:   Out << "getFAdd(";  break;
864         case Instruction::Sub:    Out << "getSub("; break;
865         case Instruction::FSub:   Out << "getFSub("; break;
866         case Instruction::Mul:    Out << "getMul("; break;
867         case Instruction::FMul:   Out << "getFMul("; break;
868         case Instruction::UDiv:   Out << "getUDiv("; break;
869         case Instruction::SDiv:   Out << "getSDiv("; break;
870         case Instruction::FDiv:   Out << "getFDiv("; break;
871         case Instruction::URem:   Out << "getURem("; break;
872         case Instruction::SRem:   Out << "getSRem("; break;
873         case Instruction::FRem:   Out << "getFRem("; break;
874         case Instruction::And:    Out << "getAnd("; break;
875         case Instruction::Or:     Out << "getOr("; break;
876         case Instruction::Xor:    Out << "getXor("; break;
877         case Instruction::ICmp:
878           Out << "getICmp(ICmpInst::ICMP_";
879           switch (CE->getPredicate()) {
880           case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
881           case ICmpInst::ICMP_NE:  Out << "NE"; break;
882           case ICmpInst::ICMP_SLT: Out << "SLT"; break;
883           case ICmpInst::ICMP_ULT: Out << "ULT"; break;
884           case ICmpInst::ICMP_SGT: Out << "SGT"; break;
885           case ICmpInst::ICMP_UGT: Out << "UGT"; break;
886           case ICmpInst::ICMP_SLE: Out << "SLE"; break;
887           case ICmpInst::ICMP_ULE: Out << "ULE"; break;
888           case ICmpInst::ICMP_SGE: Out << "SGE"; break;
889           case ICmpInst::ICMP_UGE: Out << "UGE"; break;
890           default: error("Invalid ICmp Predicate");
891           }
892           break;
893         case Instruction::FCmp:
894           Out << "getFCmp(FCmpInst::FCMP_";
895           switch (CE->getPredicate()) {
896           case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
897           case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
898           case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
899           case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
900           case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
901           case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
902           case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
903           case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
904           case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
905           case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
906           case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
907           case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
908           case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
909           case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
910           case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
911           case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
912           default: error("Invalid FCmp Predicate");
913           }
914           break;
915         case Instruction::Shl:     Out << "getShl("; break;
916         case Instruction::LShr:    Out << "getLShr("; break;
917         case Instruction::AShr:    Out << "getAShr("; break;
918         case Instruction::Select:  Out << "getSelect("; break;
919         case Instruction::ExtractElement: Out << "getExtractElement("; break;
920         case Instruction::InsertElement:  Out << "getInsertElement("; break;
921         case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
922         default:
923           error("Invalid constant expression");
924           break;
925         }
926         Out << getCppName(CE->getOperand(0));
927         for (unsigned i = 1; i < CE->getNumOperands(); ++i)
928           Out << ", " << getCppName(CE->getOperand(i));
929         Out << ");";
930       }
931     } else {
932       error("Bad Constant");
933       Out << "Constant* " << constName << " = 0; ";
934     }
935     nl(Out);
936   }
937
938   void CppWriter::printConstants(const Module* M) {
939     // Traverse all the global variables looking for constant initializers
940     for (Module::const_global_iterator I = TheModule->global_begin(),
941            E = TheModule->global_end(); I != E; ++I)
942       if (I->hasInitializer())
943         printConstant(I->getInitializer());
944
945     // Traverse the LLVM functions looking for constants
946     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
947          FI != FE; ++FI) {
948       // Add all of the basic blocks and instructions
949       for (Function::const_iterator BB = FI->begin(),
950              E = FI->end(); BB != E; ++BB) {
951         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
952              ++I) {
953           for (unsigned i = 0; i < I->getNumOperands(); ++i) {
954             if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
955               printConstant(C);
956             }
957           }
958         }
959       }
960     }
961   }
962
963   void CppWriter::printVariableUses(const GlobalVariable *GV) {
964     nl(Out) << "// Type Definitions";
965     nl(Out);
966     printType(GV->getType());
967     if (GV->hasInitializer()) {
968       Constant* Init = GV->getInitializer();
969       printType(Init->getType());
970       if (Function* F = dyn_cast<Function>(Init)) {
971         nl(Out)<< "/ Function Declarations"; nl(Out);
972         printFunctionHead(F);
973       } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
974         nl(Out) << "// Global Variable Declarations"; nl(Out);
975         printVariableHead(gv);
976       } else  {
977         nl(Out) << "// Constant Definitions"; nl(Out);
978         printConstant(gv);
979       }
980       if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
981         nl(Out) << "// Global Variable Definitions"; nl(Out);
982         printVariableBody(gv);
983       }
984     }
985   }
986
987   void CppWriter::printVariableHead(const GlobalVariable *GV) {
988     nl(Out) << "GlobalVariable* " << getCppName(GV);
989     if (is_inline) {
990       Out << " = mod->getGlobalVariable(";
991       printEscapedString(GV->getName());
992       Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
993       nl(Out) << "if (!" << getCppName(GV) << ") {";
994       in(); nl(Out) << getCppName(GV);
995     }
996     Out << " = new GlobalVariable(/*Module=*/*mod";
997     nl(Out) << "/*Type=*/";
998     printCppName(GV->getType()->getElementType());
999     Out << ",";
1000     nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1001     Out << ",";
1002     nl(Out) << "/*Linkage=*/";
1003     printLinkageType(GV->getLinkage());
1004     Out << ",";
1005     nl(Out) << "/*Initializer=*/0, ";
1006     if (GV->hasInitializer()) {
1007       Out << "// has initializer, specified below";
1008     }
1009     nl(Out) << "/*Name=*/\"";
1010     printEscapedString(GV->getName());
1011     Out << "\");";
1012     nl(Out);
1013
1014     if (GV->hasSection()) {
1015       printCppName(GV);
1016       Out << "->setSection(\"";
1017       printEscapedString(GV->getSection());
1018       Out << "\");";
1019       nl(Out);
1020     }
1021     if (GV->getAlignment()) {
1022       printCppName(GV);
1023       Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1024       nl(Out);
1025     }
1026     if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1027       printCppName(GV);
1028       Out << "->setVisibility(";
1029       printVisibilityType(GV->getVisibility());
1030       Out << ");";
1031       nl(Out);
1032     }
1033     if (is_inline) {
1034       out(); Out << "}"; nl(Out);
1035     }
1036   }
1037
1038   void CppWriter::printVariableBody(const GlobalVariable *GV) {
1039     if (GV->hasInitializer()) {
1040       printCppName(GV);
1041       Out << "->setInitializer(";
1042       Out << getCppName(GV->getInitializer()) << ");";
1043       nl(Out);
1044     }
1045   }
1046
1047   std::string CppWriter::getOpName(Value* V) {
1048     if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1049       return getCppName(V);
1050
1051     // See if its alread in the map of forward references, if so just return the
1052     // name we already set up for it
1053     ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1054     if (I != ForwardRefs.end())
1055       return I->second;
1056
1057     // This is a new forward reference. Generate a unique name for it
1058     std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1059
1060     // Yes, this is a hack. An Argument is the smallest instantiable value that
1061     // we can make as a placeholder for the real value. We'll replace these
1062     // Argument instances later.
1063     Out << "Argument* " << result << " = new Argument("
1064         << getCppName(V->getType()) << ");";
1065     nl(Out);
1066     ForwardRefs[V] = result;
1067     return result;
1068   }
1069
1070   // printInstruction - This member is called for each Instruction in a function.
1071   void CppWriter::printInstruction(const Instruction *I,
1072                                    const std::string& bbname) {
1073     std::string iName(getCppName(I));
1074
1075     // Before we emit this instruction, we need to take care of generating any
1076     // forward references. So, we get the names of all the operands in advance
1077     std::string* opNames = new std::string[I->getNumOperands()];
1078     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1079       opNames[i] = getOpName(I->getOperand(i));
1080     }
1081
1082     switch (I->getOpcode()) {
1083     default:
1084       error("Invalid instruction");
1085       break;
1086
1087     case Instruction::Ret: {
1088       const ReturnInst* ret =  cast<ReturnInst>(I);
1089       Out << "ReturnInst::Create("
1090           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1091       break;
1092     }
1093     case Instruction::Br: {
1094       const BranchInst* br = cast<BranchInst>(I);
1095       Out << "BranchInst::Create(" ;
1096       if (br->getNumOperands() == 3 ) {
1097         Out << opNames[2] << ", "
1098             << opNames[1] << ", "
1099             << opNames[0] << ", ";
1100
1101       } else if (br->getNumOperands() == 1) {
1102         Out << opNames[0] << ", ";
1103       } else {
1104         error("Branch with 2 operands?");
1105       }
1106       Out << bbname << ");";
1107       break;
1108     }
1109     case Instruction::Switch: {
1110       const SwitchInst* sw = cast<SwitchInst>(I);
1111       Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1112           << opNames[0] << ", "
1113           << opNames[1] << ", "
1114           << sw->getNumCases() << ", " << bbname << ");";
1115       nl(Out);
1116       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1117         Out << iName << "->addCase("
1118             << opNames[i] << ", "
1119             << opNames[i+1] << ");";
1120         nl(Out);
1121       }
1122       break;
1123     }
1124     case Instruction::Invoke: {
1125       const InvokeInst* inv = cast<InvokeInst>(I);
1126       Out << "std::vector<Value*> " << iName << "_params;";
1127       nl(Out);
1128       for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1129         Out << iName << "_params.push_back("
1130             << opNames[i] << ");";
1131         nl(Out);
1132       }
1133       Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1134           << opNames[0] << ", "
1135           << opNames[1] << ", "
1136           << opNames[2] << ", "
1137           << iName << "_params.begin(), " << iName << "_params.end(), \"";
1138       printEscapedString(inv->getName());
1139       Out << "\", " << bbname << ");";
1140       nl(Out) << iName << "->setCallingConv(";
1141       printCallingConv(inv->getCallingConv());
1142       Out << ");";
1143       printAttributes(inv->getAttributes(), iName);
1144       Out << iName << "->setAttributes(" << iName << "_PAL);";
1145       nl(Out);
1146       break;
1147     }
1148     case Instruction::Unwind: {
1149       Out << "new UnwindInst("
1150           << bbname << ");";
1151       break;
1152     }
1153     case Instruction::Unreachable:{
1154       Out << "new UnreachableInst("
1155           << bbname << ");";
1156       break;
1157     }
1158     case Instruction::Add:
1159     case Instruction::FAdd:
1160     case Instruction::Sub:
1161     case Instruction::FSub:
1162     case Instruction::Mul:
1163     case Instruction::FMul:
1164     case Instruction::UDiv:
1165     case Instruction::SDiv:
1166     case Instruction::FDiv:
1167     case Instruction::URem:
1168     case Instruction::SRem:
1169     case Instruction::FRem:
1170     case Instruction::And:
1171     case Instruction::Or:
1172     case Instruction::Xor:
1173     case Instruction::Shl:
1174     case Instruction::LShr:
1175     case Instruction::AShr:{
1176       Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1177       switch (I->getOpcode()) {
1178       case Instruction::Add: Out << "Instruction::Add"; break;
1179       case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1180       case Instruction::Sub: Out << "Instruction::Sub"; break;
1181       case Instruction::FSub: Out << "Instruction::FSub"; break;
1182       case Instruction::Mul: Out << "Instruction::Mul"; break;
1183       case Instruction::FMul: Out << "Instruction::FMul"; break;
1184       case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1185       case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1186       case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1187       case Instruction::URem:Out << "Instruction::URem"; break;
1188       case Instruction::SRem:Out << "Instruction::SRem"; break;
1189       case Instruction::FRem:Out << "Instruction::FRem"; break;
1190       case Instruction::And: Out << "Instruction::And"; break;
1191       case Instruction::Or:  Out << "Instruction::Or";  break;
1192       case Instruction::Xor: Out << "Instruction::Xor"; break;
1193       case Instruction::Shl: Out << "Instruction::Shl"; break;
1194       case Instruction::LShr:Out << "Instruction::LShr"; break;
1195       case Instruction::AShr:Out << "Instruction::AShr"; break;
1196       default: Out << "Instruction::BadOpCode"; break;
1197       }
1198       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1199       printEscapedString(I->getName());
1200       Out << "\", " << bbname << ");";
1201       break;
1202     }
1203     case Instruction::FCmp: {
1204       Out << "FCmpInst* " << iName << " = new FCmpInst(";
1205       switch (cast<FCmpInst>(I)->getPredicate()) {
1206       case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1207       case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1208       case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1209       case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1210       case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1211       case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1212       case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1213       case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1214       case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1215       case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1216       case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1217       case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1218       case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1219       case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1220       case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1221       case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1222       default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1223       }
1224       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1225       printEscapedString(I->getName());
1226       Out << "\", " << bbname << ");";
1227       break;
1228     }
1229     case Instruction::ICmp: {
1230       Out << "ICmpInst* " << iName << " = new ICmpInst(";
1231       switch (cast<ICmpInst>(I)->getPredicate()) {
1232       case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1233       case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1234       case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1235       case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1236       case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1237       case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1238       case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1239       case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1240       case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1241       case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1242       default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1243       }
1244       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1245       printEscapedString(I->getName());
1246       Out << "\", " << bbname << ");";
1247       break;
1248     }
1249     case Instruction::Malloc: {
1250       const MallocInst* mallocI = cast<MallocInst>(I);
1251       Out << "MallocInst* " << iName << " = new MallocInst("
1252           << getCppName(mallocI->getAllocatedType()) << ", ";
1253       if (mallocI->isArrayAllocation())
1254         Out << opNames[0] << ", " ;
1255       Out << "\"";
1256       printEscapedString(mallocI->getName());
1257       Out << "\", " << bbname << ");";
1258       if (mallocI->getAlignment())
1259         nl(Out) << iName << "->setAlignment("
1260             << mallocI->getAlignment() << ");";
1261       break;
1262     }
1263     case Instruction::Free: {
1264       Out << "FreeInst* " << iName << " = new FreeInst("
1265           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1266       break;
1267     }
1268     case Instruction::Alloca: {
1269       const AllocaInst* allocaI = cast<AllocaInst>(I);
1270       Out << "AllocaInst* " << iName << " = new AllocaInst("
1271           << getCppName(allocaI->getAllocatedType()) << ", ";
1272       if (allocaI->isArrayAllocation())
1273         Out << opNames[0] << ", ";
1274       Out << "\"";
1275       printEscapedString(allocaI->getName());
1276       Out << "\", " << bbname << ");";
1277       if (allocaI->getAlignment())
1278         nl(Out) << iName << "->setAlignment("
1279             << allocaI->getAlignment() << ");";
1280       break;
1281     }
1282     case Instruction::Load:{
1283       const LoadInst* load = cast<LoadInst>(I);
1284       Out << "LoadInst* " << iName << " = new LoadInst("
1285           << opNames[0] << ", \"";
1286       printEscapedString(load->getName());
1287       Out << "\", " << (load->isVolatile() ? "true" : "false" )
1288           << ", " << bbname << ");";
1289       break;
1290     }
1291     case Instruction::Store: {
1292       const StoreInst* store = cast<StoreInst>(I);
1293       Out << " new StoreInst("
1294           << opNames[0] << ", "
1295           << opNames[1] << ", "
1296           << (store->isVolatile() ? "true" : "false")
1297           << ", " << bbname << ");";
1298       break;
1299     }
1300     case Instruction::GetElementPtr: {
1301       const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1302       if (gep->getNumOperands() <= 2) {
1303         Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1304             << opNames[0];
1305         if (gep->getNumOperands() == 2)
1306           Out << ", " << opNames[1];
1307       } else {
1308         Out << "std::vector<Value*> " << iName << "_indices;";
1309         nl(Out);
1310         for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1311           Out << iName << "_indices.push_back("
1312               << opNames[i] << ");";
1313           nl(Out);
1314         }
1315         Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1316             << opNames[0] << ", " << iName << "_indices.begin(), "
1317             << iName << "_indices.end()";
1318       }
1319       Out << ", \"";
1320       printEscapedString(gep->getName());
1321       Out << "\", " << bbname << ");";
1322       break;
1323     }
1324     case Instruction::PHI: {
1325       const PHINode* phi = cast<PHINode>(I);
1326
1327       Out << "PHINode* " << iName << " = PHINode::Create("
1328           << getCppName(phi->getType()) << ", \"";
1329       printEscapedString(phi->getName());
1330       Out << "\", " << bbname << ");";
1331       nl(Out) << iName << "->reserveOperandSpace("
1332         << phi->getNumIncomingValues()
1333           << ");";
1334       nl(Out);
1335       for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1336         Out << iName << "->addIncoming("
1337             << opNames[i] << ", " << opNames[i+1] << ");";
1338         nl(Out);
1339       }
1340       break;
1341     }
1342     case Instruction::Trunc:
1343     case Instruction::ZExt:
1344     case Instruction::SExt:
1345     case Instruction::FPTrunc:
1346     case Instruction::FPExt:
1347     case Instruction::FPToUI:
1348     case Instruction::FPToSI:
1349     case Instruction::UIToFP:
1350     case Instruction::SIToFP:
1351     case Instruction::PtrToInt:
1352     case Instruction::IntToPtr:
1353     case Instruction::BitCast: {
1354       const CastInst* cst = cast<CastInst>(I);
1355       Out << "CastInst* " << iName << " = new ";
1356       switch (I->getOpcode()) {
1357       case Instruction::Trunc:    Out << "TruncInst"; break;
1358       case Instruction::ZExt:     Out << "ZExtInst"; break;
1359       case Instruction::SExt:     Out << "SExtInst"; break;
1360       case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1361       case Instruction::FPExt:    Out << "FPExtInst"; break;
1362       case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1363       case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1364       case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1365       case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1366       case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1367       case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1368       case Instruction::BitCast:  Out << "BitCastInst"; break;
1369       default: assert(!"Unreachable"); break;
1370       }
1371       Out << "(" << opNames[0] << ", "
1372           << getCppName(cst->getType()) << ", \"";
1373       printEscapedString(cst->getName());
1374       Out << "\", " << bbname << ");";
1375       break;
1376     }
1377     case Instruction::Call:{
1378       const CallInst* call = cast<CallInst>(I);
1379       if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1380         Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1381             << getCppName(ila->getFunctionType()) << ", \""
1382             << ila->getAsmString() << "\", \""
1383             << ila->getConstraintString() << "\","
1384             << (ila->hasSideEffects() ? "true" : "false") << ");";
1385         nl(Out);
1386       }
1387       if (call->getNumOperands() > 2) {
1388         Out << "std::vector<Value*> " << iName << "_params;";
1389         nl(Out);
1390         for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1391           Out << iName << "_params.push_back(" << opNames[i] << ");";
1392           nl(Out);
1393         }
1394         Out << "CallInst* " << iName << " = CallInst::Create("
1395             << opNames[0] << ", " << iName << "_params.begin(), "
1396             << iName << "_params.end(), \"";
1397       } else if (call->getNumOperands() == 2) {
1398         Out << "CallInst* " << iName << " = CallInst::Create("
1399             << opNames[0] << ", " << opNames[1] << ", \"";
1400       } else {
1401         Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1402             << ", \"";
1403       }
1404       printEscapedString(call->getName());
1405       Out << "\", " << bbname << ");";
1406       nl(Out) << iName << "->setCallingConv(";
1407       printCallingConv(call->getCallingConv());
1408       Out << ");";
1409       nl(Out) << iName << "->setTailCall("
1410           << (call->isTailCall() ? "true":"false");
1411       Out << ");";
1412       printAttributes(call->getAttributes(), iName);
1413       Out << iName << "->setAttributes(" << iName << "_PAL);";
1414       nl(Out);
1415       break;
1416     }
1417     case Instruction::Select: {
1418       const SelectInst* sel = cast<SelectInst>(I);
1419       Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1420       Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1421       printEscapedString(sel->getName());
1422       Out << "\", " << bbname << ");";
1423       break;
1424     }
1425     case Instruction::UserOp1:
1426       /// FALL THROUGH
1427     case Instruction::UserOp2: {
1428       /// FIXME: What should be done here?
1429       break;
1430     }
1431     case Instruction::VAArg: {
1432       const VAArgInst* va = cast<VAArgInst>(I);
1433       Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1434           << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1435       printEscapedString(va->getName());
1436       Out << "\", " << bbname << ");";
1437       break;
1438     }
1439     case Instruction::ExtractElement: {
1440       const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1441       Out << "ExtractElementInst* " << getCppName(eei)
1442           << " = new ExtractElementInst(" << opNames[0]
1443           << ", " << opNames[1] << ", \"";
1444       printEscapedString(eei->getName());
1445       Out << "\", " << bbname << ");";
1446       break;
1447     }
1448     case Instruction::InsertElement: {
1449       const InsertElementInst* iei = cast<InsertElementInst>(I);
1450       Out << "InsertElementInst* " << getCppName(iei)
1451           << " = InsertElementInst::Create(" << opNames[0]
1452           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1453       printEscapedString(iei->getName());
1454       Out << "\", " << bbname << ");";
1455       break;
1456     }
1457     case Instruction::ShuffleVector: {
1458       const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1459       Out << "ShuffleVectorInst* " << getCppName(svi)
1460           << " = new ShuffleVectorInst(" << opNames[0]
1461           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1462       printEscapedString(svi->getName());
1463       Out << "\", " << bbname << ");";
1464       break;
1465     }
1466     case Instruction::ExtractValue: {
1467       const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1468       Out << "std::vector<unsigned> " << iName << "_indices;";
1469       nl(Out);
1470       for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1471         Out << iName << "_indices.push_back("
1472             << evi->idx_begin()[i] << ");";
1473         nl(Out);
1474       }
1475       Out << "ExtractValueInst* " << getCppName(evi)
1476           << " = ExtractValueInst::Create(" << opNames[0]
1477           << ", "
1478           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1479       printEscapedString(evi->getName());
1480       Out << "\", " << bbname << ");";
1481       break;
1482     }
1483     case Instruction::InsertValue: {
1484       const InsertValueInst *ivi = cast<InsertValueInst>(I);
1485       Out << "std::vector<unsigned> " << iName << "_indices;";
1486       nl(Out);
1487       for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1488         Out << iName << "_indices.push_back("
1489             << ivi->idx_begin()[i] << ");";
1490         nl(Out);
1491       }
1492       Out << "InsertValueInst* " << getCppName(ivi)
1493           << " = InsertValueInst::Create(" << opNames[0]
1494           << ", " << opNames[1] << ", "
1495           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1496       printEscapedString(ivi->getName());
1497       Out << "\", " << bbname << ");";
1498       break;
1499     }
1500   }
1501   DefinedValues.insert(I);
1502   nl(Out);
1503   delete [] opNames;
1504 }
1505
1506   // Print out the types, constants and declarations needed by one function
1507   void CppWriter::printFunctionUses(const Function* F) {
1508     nl(Out) << "// Type Definitions"; nl(Out);
1509     if (!is_inline) {
1510       // Print the function's return type
1511       printType(F->getReturnType());
1512
1513       // Print the function's function type
1514       printType(F->getFunctionType());
1515
1516       // Print the types of each of the function's arguments
1517       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1518            AI != AE; ++AI) {
1519         printType(AI->getType());
1520       }
1521     }
1522
1523     // Print type definitions for every type referenced by an instruction and
1524     // make a note of any global values or constants that are referenced
1525     SmallPtrSet<GlobalValue*,64> gvs;
1526     SmallPtrSet<Constant*,64> consts;
1527     for (Function::const_iterator BB = F->begin(), BE = F->end();
1528          BB != BE; ++BB){
1529       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1530            I != E; ++I) {
1531         // Print the type of the instruction itself
1532         printType(I->getType());
1533
1534         // Print the type of each of the instruction's operands
1535         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1536           Value* operand = I->getOperand(i);
1537           printType(operand->getType());
1538
1539           // If the operand references a GVal or Constant, make a note of it
1540           if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1541             gvs.insert(GV);
1542             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1543               if (GVar->hasInitializer())
1544                 consts.insert(GVar->getInitializer());
1545           } else if (Constant* C = dyn_cast<Constant>(operand))
1546             consts.insert(C);
1547         }
1548       }
1549     }
1550
1551     // Print the function declarations for any functions encountered
1552     nl(Out) << "// Function Declarations"; nl(Out);
1553     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1554          I != E; ++I) {
1555       if (Function* Fun = dyn_cast<Function>(*I)) {
1556         if (!is_inline || Fun != F)
1557           printFunctionHead(Fun);
1558       }
1559     }
1560
1561     // Print the global variable declarations for any variables encountered
1562     nl(Out) << "// Global Variable Declarations"; nl(Out);
1563     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1564          I != E; ++I) {
1565       if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1566         printVariableHead(F);
1567     }
1568
1569   // Print the constants found
1570     nl(Out) << "// Constant Definitions"; nl(Out);
1571     for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1572            E = consts.end(); I != E; ++I) {
1573       printConstant(*I);
1574     }
1575
1576     // Process the global variables definitions now that all the constants have
1577     // been emitted. These definitions just couple the gvars with their constant
1578     // initializers.
1579     nl(Out) << "// Global Variable Definitions"; nl(Out);
1580     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1581          I != E; ++I) {
1582       if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1583         printVariableBody(GV);
1584     }
1585   }
1586
1587   void CppWriter::printFunctionHead(const Function* F) {
1588     nl(Out) << "Function* " << getCppName(F);
1589     if (is_inline) {
1590       Out << " = mod->getFunction(\"";
1591       printEscapedString(F->getName());
1592       Out << "\", " << getCppName(F->getFunctionType()) << ");";
1593       nl(Out) << "if (!" << getCppName(F) << ") {";
1594       nl(Out) << getCppName(F);
1595     }
1596     Out<< " = Function::Create(";
1597     nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1598     nl(Out) << "/*Linkage=*/";
1599     printLinkageType(F->getLinkage());
1600     Out << ",";
1601     nl(Out) << "/*Name=*/\"";
1602     printEscapedString(F->getName());
1603     Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1604     nl(Out,-1);
1605     printCppName(F);
1606     Out << "->setCallingConv(";
1607     printCallingConv(F->getCallingConv());
1608     Out << ");";
1609     nl(Out);
1610     if (F->hasSection()) {
1611       printCppName(F);
1612       Out << "->setSection(\"" << F->getSection() << "\");";
1613       nl(Out);
1614     }
1615     if (F->getAlignment()) {
1616       printCppName(F);
1617       Out << "->setAlignment(" << F->getAlignment() << ");";
1618       nl(Out);
1619     }
1620     if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1621       printCppName(F);
1622       Out << "->setVisibility(";
1623       printVisibilityType(F->getVisibility());
1624       Out << ");";
1625       nl(Out);
1626     }
1627     if (F->hasGC()) {
1628       printCppName(F);
1629       Out << "->setGC(\"" << F->getGC() << "\");";
1630       nl(Out);
1631     }
1632     if (is_inline) {
1633       Out << "}";
1634       nl(Out);
1635     }
1636     printAttributes(F->getAttributes(), getCppName(F));
1637     printCppName(F);
1638     Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1639     nl(Out);
1640   }
1641
1642   void CppWriter::printFunctionBody(const Function *F) {
1643     if (F->isDeclaration())
1644       return; // external functions have no bodies.
1645
1646     // Clear the DefinedValues and ForwardRefs maps because we can't have
1647     // cross-function forward refs
1648     ForwardRefs.clear();
1649     DefinedValues.clear();
1650
1651     // Create all the argument values
1652     if (!is_inline) {
1653       if (!F->arg_empty()) {
1654         Out << "Function::arg_iterator args = " << getCppName(F)
1655             << "->arg_begin();";
1656         nl(Out);
1657       }
1658       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1659            AI != AE; ++AI) {
1660         Out << "Value* " << getCppName(AI) << " = args++;";
1661         nl(Out);
1662         if (AI->hasName()) {
1663           Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1664           nl(Out);
1665         }
1666       }
1667     }
1668
1669     // Create all the basic blocks
1670     nl(Out);
1671     for (Function::const_iterator BI = F->begin(), BE = F->end();
1672          BI != BE; ++BI) {
1673       std::string bbname(getCppName(BI));
1674       Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1675       if (BI->hasName())
1676         printEscapedString(BI->getName());
1677       Out << "\"," << getCppName(BI->getParent()) << ",0);";
1678       nl(Out);
1679     }
1680
1681     // Output all of its basic blocks... for the function
1682     for (Function::const_iterator BI = F->begin(), BE = F->end();
1683          BI != BE; ++BI) {
1684       std::string bbname(getCppName(BI));
1685       nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1686       nl(Out);
1687
1688       // Output all of the instructions in the basic block...
1689       for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1690            I != E; ++I) {
1691         printInstruction(I,bbname);
1692       }
1693     }
1694
1695     // Loop over the ForwardRefs and resolve them now that all instructions
1696     // are generated.
1697     if (!ForwardRefs.empty()) {
1698       nl(Out) << "// Resolve Forward References";
1699       nl(Out);
1700     }
1701
1702     while (!ForwardRefs.empty()) {
1703       ForwardRefMap::iterator I = ForwardRefs.begin();
1704       Out << I->second << "->replaceAllUsesWith("
1705           << getCppName(I->first) << "); delete " << I->second << ";";
1706       nl(Out);
1707       ForwardRefs.erase(I);
1708     }
1709   }
1710
1711   void CppWriter::printInline(const std::string& fname,
1712                               const std::string& func) {
1713     const Function* F = TheModule->getFunction(func);
1714     if (!F) {
1715       error(std::string("Function '") + func + "' not found in input module");
1716       return;
1717     }
1718     if (F->isDeclaration()) {
1719       error(std::string("Function '") + func + "' is external!");
1720       return;
1721     }
1722     nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1723             << getCppName(F);
1724     unsigned arg_count = 1;
1725     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1726          AI != AE; ++AI) {
1727       Out << ", Value* arg_" << arg_count;
1728     }
1729     Out << ") {";
1730     nl(Out);
1731     is_inline = true;
1732     printFunctionUses(F);
1733     printFunctionBody(F);
1734     is_inline = false;
1735     Out << "return " << getCppName(F->begin()) << ";";
1736     nl(Out) << "}";
1737     nl(Out);
1738   }
1739
1740   void CppWriter::printModuleBody() {
1741     // Print out all the type definitions
1742     nl(Out) << "// Type Definitions"; nl(Out);
1743     printTypes(TheModule);
1744
1745     // Functions can call each other and global variables can reference them so
1746     // define all the functions first before emitting their function bodies.
1747     nl(Out) << "// Function Declarations"; nl(Out);
1748     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1749          I != E; ++I)
1750       printFunctionHead(I);
1751
1752     // Process the global variables declarations. We can't initialze them until
1753     // after the constants are printed so just print a header for each global
1754     nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1755     for (Module::const_global_iterator I = TheModule->global_begin(),
1756            E = TheModule->global_end(); I != E; ++I) {
1757       printVariableHead(I);
1758     }
1759
1760     // Print out all the constants definitions. Constants don't recurse except
1761     // through GlobalValues. All GlobalValues have been declared at this point
1762     // so we can proceed to generate the constants.
1763     nl(Out) << "// Constant Definitions"; nl(Out);
1764     printConstants(TheModule);
1765
1766     // Process the global variables definitions now that all the constants have
1767     // been emitted. These definitions just couple the gvars with their constant
1768     // initializers.
1769     nl(Out) << "// Global Variable Definitions"; nl(Out);
1770     for (Module::const_global_iterator I = TheModule->global_begin(),
1771            E = TheModule->global_end(); I != E; ++I) {
1772       printVariableBody(I);
1773     }
1774
1775     // Finally, we can safely put out all of the function bodies.
1776     nl(Out) << "// Function Definitions"; nl(Out);
1777     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1778          I != E; ++I) {
1779       if (!I->isDeclaration()) {
1780         nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1781                 << ")";
1782         nl(Out) << "{";
1783         nl(Out,1);
1784         printFunctionBody(I);
1785         nl(Out,-1) << "}";
1786         nl(Out);
1787       }
1788     }
1789   }
1790
1791   void CppWriter::printProgram(const std::string& fname,
1792                                const std::string& mName) {
1793     Out << "#include <llvm/Module.h>\n";
1794     Out << "#include <llvm/DerivedTypes.h>\n";
1795     Out << "#include <llvm/Constants.h>\n";
1796     Out << "#include <llvm/GlobalVariable.h>\n";
1797     Out << "#include <llvm/Function.h>\n";
1798     Out << "#include <llvm/CallingConv.h>\n";
1799     Out << "#include <llvm/BasicBlock.h>\n";
1800     Out << "#include <llvm/Instructions.h>\n";
1801     Out << "#include <llvm/InlineAsm.h>\n";
1802     Out << "#include <llvm/Support/FormattedStream.h>\n";
1803     Out << "#include <llvm/Support/MathExtras.h>\n";
1804     Out << "#include <llvm/Pass.h>\n";
1805     Out << "#include <llvm/PassManager.h>\n";
1806     Out << "#include <llvm/ADT/SmallVector.h>\n";
1807     Out << "#include <llvm/Analysis/Verifier.h>\n";
1808     Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1809     Out << "#include <algorithm>\n";
1810     Out << "using namespace llvm;\n\n";
1811     Out << "Module* " << fname << "();\n\n";
1812     Out << "int main(int argc, char**argv) {\n";
1813     Out << "  Module* Mod = " << fname << "();\n";
1814     Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1815     Out << "  outs().flush();\n";
1816     Out << "  PassManager PM;\n";
1817     Out << "  PM.add(createPrintModulePass(&outs()));\n";
1818     Out << "  PM.run(*Mod);\n";
1819     Out << "  return 0;\n";
1820     Out << "}\n\n";
1821     printModule(fname,mName);
1822   }
1823
1824   void CppWriter::printModule(const std::string& fname,
1825                               const std::string& mName) {
1826     nl(Out) << "Module* " << fname << "() {";
1827     nl(Out,1) << "// Module Construction";
1828     nl(Out) << "Module* mod = new Module(\"";
1829     printEscapedString(mName);
1830     Out << "\");";
1831     if (!TheModule->getTargetTriple().empty()) {
1832       nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1833     }
1834     if (!TheModule->getTargetTriple().empty()) {
1835       nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1836               << "\");";
1837     }
1838
1839     if (!TheModule->getModuleInlineAsm().empty()) {
1840       nl(Out) << "mod->setModuleInlineAsm(\"";
1841       printEscapedString(TheModule->getModuleInlineAsm());
1842       Out << "\");";
1843     }
1844     nl(Out);
1845
1846     // Loop over the dependent libraries and emit them.
1847     Module::lib_iterator LI = TheModule->lib_begin();
1848     Module::lib_iterator LE = TheModule->lib_end();
1849     while (LI != LE) {
1850       Out << "mod->addLibrary(\"" << *LI << "\");";
1851       nl(Out);
1852       ++LI;
1853     }
1854     printModuleBody();
1855     nl(Out) << "return mod;";
1856     nl(Out,-1) << "}";
1857     nl(Out);
1858   }
1859
1860   void CppWriter::printContents(const std::string& fname,
1861                                 const std::string& mName) {
1862     Out << "\nModule* " << fname << "(Module *mod) {\n";
1863     Out << "\nmod->setModuleIdentifier(\"";
1864     printEscapedString(mName);
1865     Out << "\");\n";
1866     printModuleBody();
1867     Out << "\nreturn mod;\n";
1868     Out << "\n}\n";
1869   }
1870
1871   void CppWriter::printFunction(const std::string& fname,
1872                                 const std::string& funcName) {
1873     const Function* F = TheModule->getFunction(funcName);
1874     if (!F) {
1875       error(std::string("Function '") + funcName + "' not found in input module");
1876       return;
1877     }
1878     Out << "\nFunction* " << fname << "(Module *mod) {\n";
1879     printFunctionUses(F);
1880     printFunctionHead(F);
1881     printFunctionBody(F);
1882     Out << "return " << getCppName(F) << ";\n";
1883     Out << "}\n";
1884   }
1885
1886   void CppWriter::printFunctions() {
1887     const Module::FunctionListType &funcs = TheModule->getFunctionList();
1888     Module::const_iterator I  = funcs.begin();
1889     Module::const_iterator IE = funcs.end();
1890
1891     for (; I != IE; ++I) {
1892       const Function &func = *I;
1893       if (!func.isDeclaration()) {
1894         std::string name("define_");
1895         name += func.getName();
1896         printFunction(name, func.getName());
1897       }
1898     }
1899   }
1900
1901   void CppWriter::printVariable(const std::string& fname,
1902                                 const std::string& varName) {
1903     const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1904
1905     if (!GV) {
1906       error(std::string("Variable '") + varName + "' not found in input module");
1907       return;
1908     }
1909     Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1910     printVariableUses(GV);
1911     printVariableHead(GV);
1912     printVariableBody(GV);
1913     Out << "return " << getCppName(GV) << ";\n";
1914     Out << "}\n";
1915   }
1916
1917   void CppWriter::printType(const std::string& fname,
1918                             const std::string& typeName) {
1919     const Type* Ty = TheModule->getTypeByName(typeName);
1920     if (!Ty) {
1921       error(std::string("Type '") + typeName + "' not found in input module");
1922       return;
1923     }
1924     Out << "\nType* " << fname << "(Module *mod) {\n";
1925     printType(Ty);
1926     Out << "return " << getCppName(Ty) << ";\n";
1927     Out << "}\n";
1928   }
1929
1930   bool CppWriter::runOnModule(Module &M) {
1931     TheModule = &M;
1932
1933     // Emit a header
1934     Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1935
1936     // Get the name of the function we're supposed to generate
1937     std::string fname = FuncName.getValue();
1938
1939     // Get the name of the thing we are to generate
1940     std::string tgtname = NameToGenerate.getValue();
1941     if (GenerationType == GenModule ||
1942         GenerationType == GenContents ||
1943         GenerationType == GenProgram ||
1944         GenerationType == GenFunctions) {
1945       if (tgtname == "!bad!") {
1946         if (M.getModuleIdentifier() == "-")
1947           tgtname = "<stdin>";
1948         else
1949           tgtname = M.getModuleIdentifier();
1950       }
1951     } else if (tgtname == "!bad!")
1952       error("You must use the -for option with -gen-{function,variable,type}");
1953
1954     switch (WhatToGenerate(GenerationType)) {
1955      case GenProgram:
1956       if (fname.empty())
1957         fname = "makeLLVMModule";
1958       printProgram(fname,tgtname);
1959       break;
1960      case GenModule:
1961       if (fname.empty())
1962         fname = "makeLLVMModule";
1963       printModule(fname,tgtname);
1964       break;
1965      case GenContents:
1966       if (fname.empty())
1967         fname = "makeLLVMModuleContents";
1968       printContents(fname,tgtname);
1969       break;
1970      case GenFunction:
1971       if (fname.empty())
1972         fname = "makeLLVMFunction";
1973       printFunction(fname,tgtname);
1974       break;
1975      case GenFunctions:
1976       printFunctions();
1977       break;
1978      case GenInline:
1979       if (fname.empty())
1980         fname = "makeLLVMInline";
1981       printInline(fname,tgtname);
1982       break;
1983      case GenVariable:
1984       if (fname.empty())
1985         fname = "makeLLVMVariable";
1986       printVariable(fname,tgtname);
1987       break;
1988      case GenType:
1989       if (fname.empty())
1990         fname = "makeLLVMType";
1991       printType(fname,tgtname);
1992       break;
1993      default:
1994       error("Invalid generation option");
1995     }
1996
1997     return false;
1998   }
1999 }
2000
2001 char CppWriter::ID = 0;
2002
2003 //===----------------------------------------------------------------------===//
2004 //                       External Interface declaration
2005 //===----------------------------------------------------------------------===//
2006
2007 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2008                                                 formatted_raw_ostream &o,
2009                                                 CodeGenFileType FileType,
2010                                                 CodeGenOpt::Level OptLevel) {
2011   if (FileType != TargetMachine::AssemblyFile) return true;
2012   PM.add(new CppWriter(o));
2013   return false;
2014 }