Don't generate module definitions when the -fragment option is given.
[oota-llvm.git] / tools / llvm2cpp / CppWriter.cpp
1 //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source 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 "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instruction.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/CommandLine.h"
28 #include <algorithm>
29 #include <iostream>
30 #include <set>
31
32 using namespace llvm;
33
34 static cl::opt<std::string>
35 ModName("modname", cl::desc("Specify the module name to use"),
36         cl::value_desc("module name"));
37
38 static cl::opt<std::string>
39 FuncName("funcname", cl::desc("Specify the name of the generated function"),
40          cl::value_desc("function name"));
41
42 static cl::opt<bool>
43 Fragment("fragment", cl::desc("Don't generate a complete program"));
44
45 namespace {
46 typedef std::vector<const Type*> TypeList;
47 typedef std::map<const Type*,std::string> TypeMap;
48 typedef std::map<const Value*,std::string> ValueMap;
49 typedef std::set<std::string> NameSet;
50 typedef std::set<const Type*> TypeSet;
51 typedef std::set<const Value*> ValueSet;
52 typedef std::map<const Value*,std::string> ForwardRefMap;
53
54 class CppWriter {
55   std::ostream &Out;
56   const Module *TheModule;
57   unsigned long uniqueNum;
58   TypeMap TypeNames;
59   ValueMap ValueNames;
60   TypeMap UnresolvedTypes;
61   TypeList TypeStack;
62   NameSet UsedNames;
63   TypeSet DefinedTypes;
64   ValueSet DefinedValues;
65   ForwardRefMap ForwardRefs;
66
67 public:
68   inline CppWriter(std::ostream &o, const Module *M)
69     : Out(o), TheModule(M), uniqueNum(0), TypeNames(),
70       ValueNames(), UnresolvedTypes(), TypeStack() { }
71
72   const Module* getModule() { return TheModule; }
73
74   void printModule();
75   void printFragment();
76
77 private:
78   void printTypes(const Module* M);
79   void printConstants(const Module* M);
80   void printConstant(const Constant *CPV);
81   void printGlobalHead(const GlobalVariable *GV);
82   void printGlobalBody(const GlobalVariable *GV);
83   void printFunctionHead(const Function *F);
84   void printFunctionBody(const Function *F);
85   void printInstruction(const Instruction *I, const std::string& bbname);
86   void printSymbolTable(const SymbolTable &ST);
87   void printLinkageType(GlobalValue::LinkageTypes LT);
88   void printCallingConv(unsigned cc);
89
90   std::string getCppName(const Type* val);
91   std::string getCppName(const Value* val);
92   inline void printCppName(const Value* val);
93   inline void printCppName(const Type* val);
94   bool isOnStack(const Type*) const;
95   inline void printTypeDef(const Type* Ty);
96   bool printTypeDefInternal(const Type* Ty);
97   void printEscapedString(const std::string& str);
98
99   std::string getOpName(Value*);
100
101   void printCFP(const ConstantFP* CFP);
102 };
103
104 // printCFP - Print a floating point constant .. very carefully :)
105 // This makes sure that conversion to/from floating yields the same binary
106 // result so that we don't lose precision.
107 void 
108 CppWriter::printCFP(const ConstantFP *CFP) {
109 #if HAVE_PRINTF_A
110   char Buffer[100];
111   sprintf(Buffer, "%A", CFP->getValue());
112   if ((!strncmp(Buffer, "0x", 2) ||
113        !strncmp(Buffer, "-0x", 3) ||
114        !strncmp(Buffer, "+0x", 3)) &&
115       (atof(Buffer) == CFP->getValue()))
116     Out << Buffer;
117   else {
118 #else
119   std::string StrVal = ftostr(CFP->getValue());
120
121   while (StrVal[0] == ' ')
122     StrVal.erase(StrVal.begin());
123
124   // Check to make sure that the stringized number is not some string like "Inf"
125   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
126   if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
127       ((StrVal[0] == '-' || StrVal[0] == '+') &&
128        (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
129       (atof(StrVal.c_str()) == CFP->getValue()))
130     Out << StrVal;
131   else if (CFP->getType() == Type::DoubleTy) {
132     Out << "0x" << std::hex << DoubleToBits(CFP->getValue()) << std::dec
133         << "ULL /* " << StrVal << " */";
134   } else  {
135     Out << "0x" << std::hex << FloatToBits(CFP->getValue()) << std::dec
136         << "U /* " << StrVal << " */";
137   }
138 #endif
139 #if HAVE_PRINTF_A
140   }
141 #endif
142 }
143
144 std::string
145 CppWriter::getOpName(Value* V) {
146   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
147     return getCppName(V);
148
149   // See if its alread in the map of forward references, if so just return the
150   // name we already set up for it
151   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
152   if (I != ForwardRefs.end())
153     return I->second;
154
155   // This is a new forward reference. Generate a unique name for it
156   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
157
158   // Yes, this is a hack. An Argument is the smallest instantiable value that
159   // we can make as a placeholder for the real value. We'll replace these
160   // Argument instances later.
161   Out << "  Argument* " << result << " = new Argument(" 
162       << getCppName(V->getType()) << ");\n";
163   ForwardRefs[V] = result;
164   return result;
165 }
166
167 // printEscapedString - Print each character of the specified string, escaping
168 // it if it is not printable or if it is an escape char.
169 void 
170 CppWriter::printEscapedString(const std::string &Str) {
171   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
172     unsigned char C = Str[i];
173     if (isprint(C) && C != '"' && C != '\\') {
174       Out << C;
175     } else {
176       Out << "\\x"
177           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
178           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
179     }
180   }
181 }
182
183 inline void
184 sanitize(std::string& str) {
185   for (size_t i = 0; i < str.length(); ++i)
186     if (!isalnum(str[i]) && str[i] != '_')
187       str[i] = '_';
188 }
189
190 inline const char* 
191 getTypePrefix(const Type* Ty ) {
192   const char* prefix;
193   switch (Ty->getTypeID()) {
194     case Type::VoidTyID:     prefix = "void_"; break;
195     case Type::BoolTyID:     prefix = "bool_"; break; 
196     case Type::UByteTyID:    prefix = "ubyte_"; break;
197     case Type::SByteTyID:    prefix = "sbyte_"; break;
198     case Type::UShortTyID:   prefix = "ushort_"; break;
199     case Type::ShortTyID:    prefix = "short_"; break;
200     case Type::UIntTyID:     prefix = "uint_"; break;
201     case Type::IntTyID:      prefix = "int_"; break;
202     case Type::ULongTyID:    prefix = "ulong_"; break;
203     case Type::LongTyID:     prefix = "long_"; break;
204     case Type::FloatTyID:    prefix = "float_"; break;
205     case Type::DoubleTyID:   prefix = "double_"; break;
206     case Type::LabelTyID:    prefix = "label_"; break;
207     case Type::FunctionTyID: prefix = "func_"; break;
208     case Type::StructTyID:   prefix = "struct_"; break;
209     case Type::ArrayTyID:    prefix = "array_"; break;
210     case Type::PointerTyID:  prefix = "ptr_"; break;
211     case Type::PackedTyID:   prefix = "packed_"; break;
212     case Type::OpaqueTyID:   prefix = "opaque_"; break;
213     default:                 prefix = "other_"; break;
214   }
215   return prefix;
216 }
217
218 std::string
219 CppWriter::getCppName(const Value* val) {
220   std::string name;
221   ValueMap::iterator I = ValueNames.find(val);
222   if (I != ValueNames.end() && I->first == val)
223     return  I->second;
224
225   if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
226     name = std::string("gvar_") + 
227            getTypePrefix(GV->getType()->getElementType());
228   } else if (const Function* F = dyn_cast<Function>(val)) {
229     name = std::string("func_");
230   } else if (const Constant* C = dyn_cast<Constant>(val)) {
231     name = std::string("const_") + getTypePrefix(C->getType());
232   } else {
233     name = getTypePrefix(val->getType());
234   }
235   name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
236   sanitize(name);
237   NameSet::iterator NI = UsedNames.find(name);
238   if (NI != UsedNames.end())
239     name += std::string("_") + utostr(uniqueNum++);
240   UsedNames.insert(name);
241   return ValueNames[val] = name;
242 }
243
244 void
245 CppWriter::printCppName(const Value* val) {
246   printEscapedString(getCppName(val));
247 }
248
249 void
250 CppWriter::printCppName(const Type* Ty)
251 {
252   printEscapedString(getCppName(Ty));
253 }
254
255 // Gets the C++ name for a type. Returns true if we already saw the type,
256 // false otherwise.
257 //
258 inline const std::string* 
259 findTypeName(const SymbolTable& ST, const Type* Ty)
260 {
261   SymbolTable::type_const_iterator TI = ST.type_begin();
262   SymbolTable::type_const_iterator TE = ST.type_end();
263   for (;TI != TE; ++TI)
264     if (TI->second == Ty)
265       return &(TI->first);
266   return 0;
267 }
268
269 std::string
270 CppWriter::getCppName(const Type* Ty)
271 {
272   // First, handle the primitive types .. easy
273   if (Ty->isPrimitiveType()) {
274     switch (Ty->getTypeID()) {
275       case Type::VoidTyID:     return "Type::VoidTy";
276       case Type::BoolTyID:     return "Type::BoolTy"; 
277       case Type::UByteTyID:    return "Type::UByteTy";
278       case Type::SByteTyID:    return "Type::SByteTy";
279       case Type::UShortTyID:   return "Type::UShortTy";
280       case Type::ShortTyID:    return "Type::ShortTy";
281       case Type::UIntTyID:     return "Type::UIntTy";
282       case Type::IntTyID:      return "Type::IntTy";
283       case Type::ULongTyID:    return "Type::ULongTy";
284       case Type::LongTyID:     return "Type::LongTy";
285       case Type::FloatTyID:    return "Type::FloatTy";
286       case Type::DoubleTyID:   return "Type::DoubleTy";
287       case Type::LabelTyID:    return "Type::LabelTy";
288       default:
289         assert(!"Can't get here");
290         break;
291     }
292     return "Type::VoidTy"; // shouldn't be returned, but make it sensible
293   }
294
295   // Now, see if we've seen the type before and return that
296   TypeMap::iterator I = TypeNames.find(Ty);
297   if (I != TypeNames.end())
298     return I->second;
299
300   // Okay, let's build a new name for this type. Start with a prefix
301   const char* prefix = 0;
302   switch (Ty->getTypeID()) {
303     case Type::FunctionTyID:    prefix = "FuncTy_"; break;
304     case Type::StructTyID:      prefix = "StructTy_"; break;
305     case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
306     case Type::PointerTyID:     prefix = "PointerTy_"; break;
307     case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
308     case Type::PackedTyID:      prefix = "PackedTy_"; break;
309     default:                    prefix = "OtherTy_"; break; // prevent breakage
310   }
311
312   // See if the type has a name in the symboltable and build accordingly
313   const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
314   std::string name;
315   if (tName) 
316     name = std::string(prefix) + *tName;
317   else
318     name = std::string(prefix) + utostr(uniqueNum++);
319   sanitize(name);
320
321   // Save the name
322   return TypeNames[Ty] = name;
323 }
324
325 void CppWriter::printFragment() {
326   // Print out all the type definitions
327   Out << "\n// Type Definitions\n";
328   printTypes(TheModule);
329
330   // Functions can call each other and global variables can reference them so 
331   // define all the functions first before emitting their function bodies.
332   Out << "\n// Function Declarations\n";
333   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 
334        I != E; ++I)
335     printFunctionHead(I);
336
337   // Process the global variables declarations. We can't initialze them until
338   // after the constants are printed so just print a header for each global
339   Out << "\n// Global Variable Declarations\n";
340   for (Module::const_global_iterator I = TheModule->global_begin(), 
341        E = TheModule->global_end(); I != E; ++I) {
342     printGlobalHead(I);
343   }
344
345   // Print out all the constants definitions. Constants don't recurse except
346   // through GlobalValues. All GlobalValues have been declared at this point
347   // so we can proceed to generate the constants.
348   Out << "\n// Constant Definitions\n";
349   printConstants(TheModule);
350
351   // Process the global variables definitions now that all the constants have
352   // been emitted. These definitions just couple the gvars with their constant
353   // initializers.
354   Out << "\n// Global Variable Definitions\n";
355   for (Module::const_global_iterator I = TheModule->global_begin(), 
356        E = TheModule->global_end(); I != E; ++I) {
357     printGlobalBody(I);
358   }
359
360   // Finally, we can safely put out all of the function bodies.
361   Out << "\n// Function Definitions\n";
362   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 
363        I != E; ++I) {
364     if (!I->isExternal()) {
365       Out << "\n// Function: " << I->getName() << " (" << getCppName(I) 
366           << ")\n{\n";
367       printFunctionBody(I);
368       Out << "}\n";
369     }
370   }
371 }
372
373 void CppWriter::printModule() {
374   Out << "\n// Module Construction\n";
375   Out << "Module* mod = new Module(\"";
376   if (!ModName.empty())
377     printEscapedString(ModName);
378   else if (TheModule->getModuleIdentifier() == "-")
379     printEscapedString("<stdin>");
380   else 
381     printEscapedString(TheModule->getModuleIdentifier());
382   Out << "\");\n";
383   Out << "mod->setEndianness(";
384   switch (TheModule->getEndianness()) {
385     case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
386     case Module::BigEndian:    Out << "Module::BigEndian);\n";    break;
387     case Module::AnyEndianness:Out << "Module::AnyEndianness);\n";  break;
388   }
389   Out << "mod->setPointerSize(";
390   switch (TheModule->getPointerSize()) {
391     case Module::Pointer32:      Out << "Module::Pointer32);\n"; break;
392     case Module::Pointer64:      Out << "Module::Pointer64);\n"; break;
393     case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
394   }
395   if (!TheModule->getTargetTriple().empty())
396     Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() 
397         << "\");\n";
398
399   if (!TheModule->getModuleInlineAsm().empty()) {
400     Out << "mod->setModuleInlineAsm(\"";
401     printEscapedString(TheModule->getModuleInlineAsm());
402     Out << "\");\n";
403   }
404   
405   // Loop over the dependent libraries and emit them.
406   Module::lib_iterator LI = TheModule->lib_begin();
407   Module::lib_iterator LE = TheModule->lib_end();
408   while (LI != LE) {
409     Out << "mod->addLibrary(\"" << *LI << "\");\n";
410     ++LI;
411   }
412   printFragment();
413 }
414
415 void
416 CppWriter::printCallingConv(unsigned cc){
417   // Print the calling convention.
418   switch (cc) {
419     case CallingConv::C:     Out << "CallingConv::C"; break;
420     case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
421     case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
422     case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
423     case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
424     default:                 Out << cc; break;
425   }
426 }
427
428 void 
429 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
430   switch (LT) {
431     case GlobalValue::InternalLinkage:  
432       Out << "GlobalValue::InternalLinkage"; break;
433     case GlobalValue::LinkOnceLinkage:  
434       Out << "GlobalValue::LinkOnceLinkage "; break;
435     case GlobalValue::WeakLinkage:      
436       Out << "GlobalValue::WeakLinkage"; break;
437     case GlobalValue::AppendingLinkage: 
438       Out << "GlobalValue::AppendingLinkage"; break;
439     case GlobalValue::ExternalLinkage: 
440       Out << "GlobalValue::ExternalLinkage"; break;
441     case GlobalValue::GhostLinkage:
442       Out << "GlobalValue::GhostLinkage"; break;
443   }
444 }
445
446 void CppWriter::printGlobalHead(const GlobalVariable *GV) {
447   Out << "\n";
448   Out << "GlobalVariable* ";
449   printCppName(GV);
450   Out << " = new GlobalVariable(\n";
451   Out << "  /*Type=*/";
452   printCppName(GV->getType()->getElementType());
453   Out << ",\n";
454   Out << "  /*isConstant=*/" << (GV->isConstant()?"true":"false") 
455       << ",\n  /*Linkage=*/";
456   printLinkageType(GV->getLinkage());
457   Out << ",\n  /*Initializer=*/0, ";
458   if (GV->hasInitializer()) {
459     Out << "// has initializer, specified below";
460   }
461   Out << "\n  /*Name=*/\"";
462   printEscapedString(GV->getName());
463   Out << "\",\n  mod);\n";
464
465   if (GV->hasSection()) {
466     printCppName(GV);
467     Out << "->setSection(\"";
468     printEscapedString(GV->getSection());
469     Out << "\");\n";
470   }
471   if (GV->getAlignment()) {
472     printCppName(GV);
473     Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
474   };
475 }
476
477 void 
478 CppWriter::printGlobalBody(const GlobalVariable *GV) {
479   if (GV->hasInitializer()) {
480     printCppName(GV);
481     Out << "->setInitializer(";
482     //if (!isa<GlobalValue(GV->getInitializer()))
483     //else 
484       Out << getCppName(GV->getInitializer()) << ");\n";
485   }
486 }
487
488 bool
489 CppWriter::isOnStack(const Type* Ty) const {
490   TypeList::const_iterator TI = 
491     std::find(TypeStack.begin(),TypeStack.end(),Ty);
492   return TI != TypeStack.end();
493 }
494
495 // Prints a type definition. Returns true if it could not resolve all the types
496 // in the definition but had to use a forward reference.
497 void
498 CppWriter::printTypeDef(const Type* Ty) {
499   assert(TypeStack.empty());
500   TypeStack.clear();
501   printTypeDefInternal(Ty);
502   assert(TypeStack.empty());
503 }
504
505 bool
506 CppWriter::printTypeDefInternal(const Type* Ty) {
507   // We don't print definitions for primitive types
508   if (Ty->isPrimitiveType())
509     return false;
510
511   // If we already defined this type, we don't need to define it again.
512   if (DefinedTypes.find(Ty) != DefinedTypes.end())
513     return false;
514
515   // Everything below needs the name for the type so get it now.
516   std::string typeName(getCppName(Ty));
517
518   // Search the type stack for recursion. If we find it, then generate this
519   // as an OpaqueType, but make sure not to do this multiple times because
520   // the type could appear in multiple places on the stack. Once the opaque
521   // definition is issued, it must not be re-issued. Consequently we have to
522   // check the UnresolvedTypes list as well.
523   if (isOnStack(Ty)) {
524     TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
525     if (I == UnresolvedTypes.end()) {
526       Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
527       UnresolvedTypes[Ty] = typeName;
528     }
529     return true;
530   }
531
532   // We're going to print a derived type which, by definition, contains other
533   // types. So, push this one we're printing onto the type stack to assist with
534   // recursive definitions.
535   TypeStack.push_back(Ty);
536
537   // Print the type definition
538   switch (Ty->getTypeID()) {
539     case Type::FunctionTyID:  {
540       const FunctionType* FT = cast<FunctionType>(Ty);
541       Out << "std::vector<const Type*>" << typeName << "_args;\n";
542       FunctionType::param_iterator PI = FT->param_begin();
543       FunctionType::param_iterator PE = FT->param_end();
544       for (; PI != PE; ++PI) {
545         const Type* argTy = static_cast<const Type*>(*PI);
546         bool isForward = printTypeDefInternal(argTy);
547         std::string argName(getCppName(argTy));
548         Out << typeName << "_args.push_back(" << argName;
549         if (isForward)
550           Out << "_fwd";
551         Out << ");\n";
552       }
553       bool isForward = printTypeDefInternal(FT->getReturnType());
554       std::string retTypeName(getCppName(FT->getReturnType()));
555       Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
556           << "  /*Result=*/" << retTypeName;
557       if (isForward)
558         Out << "_fwd";
559       Out << ",\n  /*Params=*/" << typeName << "_args,\n  /*isVarArg=*/"
560           << (FT->isVarArg() ? "true" : "false") << ");\n";
561       break;
562     }
563     case Type::StructTyID: {
564       const StructType* ST = cast<StructType>(Ty);
565       Out << "std::vector<const Type*>" << typeName << "_fields;\n";
566       StructType::element_iterator EI = ST->element_begin();
567       StructType::element_iterator EE = ST->element_end();
568       for (; EI != EE; ++EI) {
569         const Type* fieldTy = static_cast<const Type*>(*EI);
570         bool isForward = printTypeDefInternal(fieldTy);
571         std::string fieldName(getCppName(fieldTy));
572         Out << typeName << "_fields.push_back(" << fieldName;
573         if (isForward)
574           Out << "_fwd";
575         Out << ");\n";
576       }
577       Out << "StructType* " << typeName << " = StructType::get("
578           << typeName << "_fields);\n";
579       break;
580     }
581     case Type::ArrayTyID: {
582       const ArrayType* AT = cast<ArrayType>(Ty);
583       const Type* ET = AT->getElementType();
584       bool isForward = printTypeDefInternal(ET);
585       std::string elemName(getCppName(ET));
586       Out << "ArrayType* " << typeName << " = ArrayType::get("
587           << elemName << (isForward ? "_fwd" : "") 
588           << ", " << utostr(AT->getNumElements()) << ");\n";
589       break;
590     }
591     case Type::PointerTyID: {
592       const PointerType* PT = cast<PointerType>(Ty);
593       const Type* ET = PT->getElementType();
594       bool isForward = printTypeDefInternal(ET);
595       std::string elemName(getCppName(ET));
596       Out << "PointerType* " << typeName << " = PointerType::get("
597           << elemName << (isForward ? "_fwd" : "") << ");\n";
598       break;
599     }
600     case Type::PackedTyID: {
601       const PackedType* PT = cast<PackedType>(Ty);
602       const Type* ET = PT->getElementType();
603       bool isForward = printTypeDefInternal(ET);
604       std::string elemName(getCppName(ET));
605       Out << "PackedType* " << typeName << " = PackedType::get("
606           << elemName << (isForward ? "_fwd" : "") 
607           << ", " << utostr(PT->getNumElements()) << ");\n";
608       break;
609     }
610     case Type::OpaqueTyID: {
611       const OpaqueType* OT = cast<OpaqueType>(Ty);
612       Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
613       break;
614     }
615     default:
616       assert(!"Invalid TypeID");
617   }
618
619   // If the type had a name, make sure we recreate it.
620   const std::string* progTypeName = 
621     findTypeName(TheModule->getSymbolTable(),Ty);
622   if (progTypeName)
623     Out << "mod->addTypeName(\"" << *progTypeName << "\", " 
624         << typeName << ");\n";
625
626   // Pop us off the type stack
627   TypeStack.pop_back();
628
629   // Indicate that this type is now defined.
630   DefinedTypes.insert(Ty);
631
632   // Early resolve as many unresolved types as possible. Search the unresolved
633   // types map for the type we just printed. Now that its definition is complete
634   // we can resolve any previous references to it. This prevents a cascade of
635   // unresolved types.
636   TypeMap::iterator I = UnresolvedTypes.find(Ty);
637   if (I != UnresolvedTypes.end()) {
638     Out << "cast<OpaqueType>(" << I->second 
639         << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
640     Out << I->second << " = cast<";
641     switch (Ty->getTypeID()) {
642       case Type::FunctionTyID: Out << "FunctionType"; break;
643       case Type::ArrayTyID:    Out << "ArrayType"; break;
644       case Type::StructTyID:   Out << "StructType"; break;
645       case Type::PackedTyID:   Out << "PackedType"; break;
646       case Type::PointerTyID:  Out << "PointerType"; break;
647       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
648       default:                 Out << "NoSuchDerivedType"; break;
649     }
650     Out << ">(" << I->second << "_fwd.get());\n\n";
651     UnresolvedTypes.erase(I);
652   }
653
654   // Finally, separate the type definition from other with a newline.
655   Out << "\n";
656
657   // We weren't a recursive type
658   return false;
659 }
660
661 void
662 CppWriter::printTypes(const Module* M) {
663
664   // Walk the symbol table and print out all its types
665   const SymbolTable& symtab = M->getSymbolTable();
666   for (SymbolTable::type_const_iterator TI = symtab.type_begin(), 
667        TE = symtab.type_end(); TI != TE; ++TI) {
668
669     // For primitive types and types already defined, just add a name
670     TypeMap::const_iterator TNI = TypeNames.find(TI->second);
671     if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
672       Out << "mod->addTypeName(\"";
673       printEscapedString(TI->first);
674       Out << "\", " << getCppName(TI->second) << ");\n";
675     // For everything else, define the type
676     } else {
677       printTypeDef(TI->second);
678     }
679   }
680
681   // Add all of the global variables to the value table...
682   for (Module::const_global_iterator I = TheModule->global_begin(), 
683        E = TheModule->global_end(); I != E; ++I) {
684     if (I->hasInitializer())
685       printTypeDef(I->getInitializer()->getType());
686     printTypeDef(I->getType());
687   }
688
689   // Add all the functions to the table
690   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
691        FI != FE; ++FI) {
692     printTypeDef(FI->getReturnType());
693     printTypeDef(FI->getFunctionType());
694     // Add all the function arguments
695     for(Function::const_arg_iterator AI = FI->arg_begin(),
696         AE = FI->arg_end(); AI != AE; ++AI) {
697       printTypeDef(AI->getType());
698     }
699
700     // Add all of the basic blocks and instructions
701     for (Function::const_iterator BB = FI->begin(),
702          E = FI->end(); BB != E; ++BB) {
703       printTypeDef(BB->getType());
704       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 
705            ++I) {
706         printTypeDef(I->getType());
707         for (unsigned i = 0; i < I->getNumOperands(); ++i)
708           printTypeDef(I->getOperand(i)->getType());
709       }
710     }
711   }
712 }
713
714 void
715 CppWriter::printConstants(const Module* M) {
716   // Add all of the global variables to the value table...
717   for (Module::const_global_iterator I = TheModule->global_begin(), 
718        E = TheModule->global_end(); I != E; ++I)
719     if (I->hasInitializer())
720       printConstant(I->getInitializer());
721
722   // Traverse the LLVM functions looking for constants
723   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
724        FI != FE; ++FI) {
725     // Add all of the basic blocks and instructions
726     for (Function::const_iterator BB = FI->begin(),
727          E = FI->end(); BB != E; ++BB) {
728       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 
729            ++I) {
730         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
731           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
732             printConstant(C);
733           }
734         }
735       }
736     }
737   }
738 }
739
740 // printConstant - Print out a constant pool entry...
741 void CppWriter::printConstant(const Constant *CV) {
742   // First, if the constant is actually a GlobalValue (variable or function) or
743   // its already in the constant list then we've printed it already and we can
744   // just return.
745   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
746     return;
747
748   const int IndentSize = 2;
749   static std::string Indent = "\n";
750   std::string constName(getCppName(CV));
751   std::string typeName(getCppName(CV->getType()));
752   if (CV->isNullValue()) {
753     Out << "Constant* " << constName << " = Constant::getNullValue("
754         << typeName << ");\n";
755     return;
756   }
757   if (isa<GlobalValue>(CV)) {
758     // Skip variables and functions, we emit them elsewhere
759     return;
760   }
761   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
762     Out << "ConstantBool* " << constName << " = ConstantBool::get(" 
763         << (CB == ConstantBool::True ? "true" : "false")
764         << ");";
765   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
766     Out << "ConstantSInt* " << constName << " = ConstantSInt::get(" 
767         << typeName << ", " << CI->getValue() << ");";
768   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
769     Out << "ConstantUInt* " << constName << " = ConstantUInt::get(" 
770         << typeName << ", " << CI->getValue() << ");";
771   } else if (isa<ConstantAggregateZero>(CV)) {
772     Out << "ConstantAggregateZero* " << constName 
773         << " = ConstantAggregateZero::get(" << typeName << ");";
774   } else if (isa<ConstantPointerNull>(CV)) {
775     Out << "ConstantPointerNull* " << constName 
776         << " = ConstanPointerNull::get(" << typeName << ");";
777   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
778     Out << "ConstantFP* " << constName << " = ConstantFP::get(" << typeName 
779         << ", ";
780     char buffer[64];
781     sprintf(buffer,"%A",CFP->getValue());
782     // We would like to output the FP constant value in exponential notation,
783     // but we cannot do this if doing so will lose precision.  Check here to
784     // make sure that we only output it in exponential format if we can parse
785     // the value back and get the same value.
786     //
787     std::string StrVal = ftostr(CFP->getValue());
788
789     // Check to make sure that the stringized number is not some string like
790     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
791     // the string matches the "[-+]?[0-9]" regex.
792     //
793     if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
794         ((StrVal[0] == '-' || StrVal[0] == '+') &&
795          (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
796         (atof(StrVal.c_str()) == CFP->getValue())) 
797     {
798       Out << StrVal;
799     } else {
800
801       // Otherwise we could not reparse it to exactly the same value, so we must
802       // output the string in hexadecimal format!
803       assert(sizeof(double) == sizeof(uint64_t) &&
804              "assuming that double is 64 bits!");
805       Out << "0x" << std::hex << DoubleToBits(CFP->getValue()) << std::dec 
806           << "ULL /* " << StrVal << " */";
807     }
808     Out << ");";
809   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
810     if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
811       Out << "Constant* " << constName << " = ConstantArray::get(\"";
812       printEscapedString(CA->getAsString());
813       // Determine if we want null termination or not.
814       if (CA->getType()->getNumElements() <= CA->getAsString().length())
815         Out << "\", false";// No null terminator
816       else
817         Out << "\", true"; // Indicate that the null terminator should be added.
818       Out << ");";
819     } else { 
820       Out << "std::vector<Constant*> " << constName << "_elems;\n";
821       unsigned N = CA->getNumOperands();
822       for (unsigned i = 0; i < N; ++i) {
823         printConstant(CA->getOperand(i)); // recurse to print operands
824         Out << constName << "_elems.push_back("
825             << getCppName(CA->getOperand(i)) << ");\n";
826       }
827       Out << "Constant* " << constName << " = ConstantArray::get(" 
828           << typeName << ", " << constName << "_elems);";
829     }
830   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
831     Out << "std::vector<Constant*> " << constName << "_fields;\n";
832     unsigned N = CS->getNumOperands();
833     for (unsigned i = 0; i < N; i++) {
834       printConstant(CS->getOperand(i));
835       Out << constName << "_fields.push_back("
836           << getCppName(CS->getOperand(i)) << ");\n";
837     }
838     Out << "Constant* " << constName << " = ConstantStruct::get(" 
839         << typeName << ", " << constName << "_fields);";
840   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
841     Out << "std::vector<Constant*> " << constName << "_elems;\n";
842     unsigned N = CP->getNumOperands();
843     for (unsigned i = 0; i < N; ++i) {
844       printConstant(CP->getOperand(i));
845       Out << constName << "_elems.push_back("
846           << getCppName(CP->getOperand(i)) << ");\n";
847     }
848     Out << "Constant* " << constName << " = ConstantPacked::get(" 
849         << typeName << ", " << constName << "_elems);";
850   } else if (isa<UndefValue>(CV)) {
851     Out << "UndefValue* " << constName << " = UndefValue::get(" 
852         << typeName << ");";
853   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
854     if (CE->getOpcode() == Instruction::GetElementPtr) {
855       Out << "std::vector<Constant*> " << constName << "_indices;\n";
856       printConstant(CE->getOperand(0));
857       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
858         printConstant(CE->getOperand(i));
859         Out << constName << "_indices.push_back("
860             << getCppName(CE->getOperand(i)) << ");\n";
861       }
862       Out << "Constant* " << constName 
863           << " = ConstantExpr::getGetElementPtr(" 
864           << getCppName(CE->getOperand(0)) << ", " 
865           << constName << "_indices);";
866     } else if (CE->getOpcode() == Instruction::Cast) {
867       printConstant(CE->getOperand(0));
868       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
869       Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
870           << ");";
871     } else {
872       unsigned N = CE->getNumOperands();
873       for (unsigned i = 0; i < N; ++i ) {
874         printConstant(CE->getOperand(i));
875       }
876       Out << "Constant* " << constName << " = ConstantExpr::";
877       switch (CE->getOpcode()) {
878         case Instruction::Add:    Out << "getAdd";  break;
879         case Instruction::Sub:    Out << "getSub"; break;
880         case Instruction::Mul:    Out << "getMul"; break;
881         case Instruction::Div:    Out << "getDiv"; break;
882         case Instruction::Rem:    Out << "getRem"; break;
883         case Instruction::And:    Out << "getAnd"; break;
884         case Instruction::Or:     Out << "getOr"; break;
885         case Instruction::Xor:    Out << "getXor"; break;
886         case Instruction::SetEQ:  Out << "getSetEQ"; break;
887         case Instruction::SetNE:  Out << "getSetNE"; break;
888         case Instruction::SetLE:  Out << "getSetLE"; break;
889         case Instruction::SetGE:  Out << "getSetGE"; break;
890         case Instruction::SetLT:  Out << "getSetLT"; break;
891         case Instruction::SetGT:  Out << "getSetGT"; break;
892         case Instruction::Shl:    Out << "getShl"; break;
893         case Instruction::Shr:    Out << "getShr"; break;
894         case Instruction::Select: Out << "getSelect"; break;
895         case Instruction::ExtractElement: Out << "getExtractElement"; break;
896         case Instruction::InsertElement:  Out << "getInsertElement"; break;
897         case Instruction::ShuffleVector:  Out << "getShuffleVector"; break;
898         default:
899           assert(!"Invalid constant expression");
900           break;
901       }
902       Out << getCppName(CE->getOperand(0));
903       for (unsigned i = 1; i < CE->getNumOperands(); ++i) 
904         Out << ", " << getCppName(CE->getOperand(i));
905       Out << ");";
906     }
907   } else {
908     assert(!"Bad Constant");
909     Out << "Constant* " << constName << " = 0; ";
910   }
911   Out << "\n";
912 }
913
914 void CppWriter::printFunctionHead(const Function* F) {
915   Out << "\nFunction* " << getCppName(F) << " = new Function(\n"
916       << "  /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
917       << "  /*Linkage=*/";
918   printLinkageType(F->getLinkage());
919   Out << ",\n  /*Name=*/\"";
920   printEscapedString(F->getName());
921   Out << "\", mod); " 
922       << (F->isExternal()? "// (external, no body)" : "") << "\n";
923   printCppName(F);
924   Out << "->setCallingConv(";
925   printCallingConv(F->getCallingConv());
926   Out << ");\n";
927   if (F->hasSection()) {
928     printCppName(F);
929     Out << "->setSection(\"" << F->getSection() << "\");\n";
930   }
931   if (F->getAlignment()) {
932     printCppName(F);
933     Out << "->setAlignment(" << F->getAlignment() << ");\n";
934   }
935 }
936
937 void CppWriter::printFunctionBody(const Function *F) {
938   if (F->isExternal())
939     return; // external functions have no bodies.
940
941   // Clear the DefinedValues and ForwardRefs maps because we can't have 
942   // cross-function forward refs
943   ForwardRefs.clear();
944   DefinedValues.clear();
945
946   // Create all the argument values
947   if (!F->arg_empty()) {
948     Out << "  Function::arg_iterator args = " << getCppName(F) 
949         << "->arg_begin();\n";
950   }
951   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
952        AI != AE; ++AI) {
953     Out << "  Value* " << getCppName(AI) << " = args++;\n";
954     if (AI->hasName())
955       Out << "  " << getCppName(AI) << "->setName(\"" << AI->getName() 
956           << "\");\n";
957   }
958
959   // Create all the basic blocks
960   Out << "\n";
961   for (Function::const_iterator BI = F->begin(), BE = F->end(); 
962        BI != BE; ++BI) {
963     std::string bbname(getCppName(BI));
964     Out << "  BasicBlock* " << bbname << " = new BasicBlock(\"";
965     if (BI->hasName())
966       printEscapedString(BI->getName());
967     Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
968   }
969
970   // Output all of its basic blocks... for the function
971   for (Function::const_iterator BI = F->begin(), BE = F->end(); 
972        BI != BE; ++BI) {
973     std::string bbname(getCppName(BI));
974     Out << "\n  // Block " << BI->getName() << " (" << bbname << ")\n";
975
976     // Output all of the instructions in the basic block...
977     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); 
978          I != E; ++I) {
979       printInstruction(I,bbname);
980     }
981   }
982
983   // Loop over the ForwardRefs and resolve them now that all instructions
984   // are generated.
985   if (!ForwardRefs.empty())
986     Out << "\n  // Resolve Forward References\n";
987   while (!ForwardRefs.empty()) {
988     ForwardRefMap::iterator I = ForwardRefs.begin();
989     Out << "  " << I->second << "->replaceAllUsesWith(" 
990         << getCppName(I->first) << "); delete " << I->second << ";\n";
991     ForwardRefs.erase(I);
992   }
993 }
994
995 // printInstruction - This member is called for each Instruction in a function.
996 void 
997 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) 
998 {
999   std::string iName(getCppName(I));
1000
1001   // Before we emit this instruction, we need to take care of generating any
1002   // forward references. So, we get the names of all the operands in advance
1003   std::string* opNames = new std::string[I->getNumOperands()];
1004   for (unsigned i = 0; i < I->getNumOperands(); i++) {
1005     opNames[i] = getOpName(I->getOperand(i));
1006   }
1007
1008   switch (I->getOpcode()) {
1009     case Instruction::Ret: {
1010       const ReturnInst* ret =  cast<ReturnInst>(I);
1011       Out << "  ReturnInst* " << iName << " = new ReturnInst("
1012           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1013       break;
1014     }
1015     case Instruction::Br: {
1016       const BranchInst* br = cast<BranchInst>(I);
1017       Out << "  BranchInst* " << iName << " = new BranchInst(" ;
1018       if (br->getNumOperands() == 3 ) {
1019         Out << opNames[0] << ", " 
1020             << opNames[1] << ", "
1021             << opNames[2] << ", ";
1022
1023       } else if (br->getNumOperands() == 1) {
1024         Out << opNames[0] << ", ";
1025       } else {
1026         assert(!"branch with 2 operands?");
1027       }
1028       Out << bbname << ");";
1029       break;
1030     }
1031     case Instruction::Switch: {
1032       const SwitchInst* sw = cast<SwitchInst>(I);
1033       Out << "  SwitchInst* " << iName << " = new SwitchInst("
1034           << opNames[0] << ", "
1035           << opNames[1] << ", "
1036           << sw->getNumCases() << ", " << bbname << ");\n";
1037       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1038         Out << "  " << iName << "->addCase(" 
1039             << opNames[i] << ", "
1040             << opNames[i+1] << ");\n";
1041       }
1042       break;
1043     }
1044     case Instruction::Invoke: {
1045       const InvokeInst* inv = cast<InvokeInst>(I);
1046       Out << "  std::vector<Value*> " << iName << "_params;\n";
1047       for (unsigned i = 3; i < inv->getNumOperands(); ++i)
1048         Out << "  " << iName << "_params.push_back("
1049             << opNames[i] << ");\n";
1050       Out << "  InvokeInst* " << iName << " = new InvokeInst("
1051           << opNames[0] << ", "
1052           << opNames[1] << ", "
1053           << opNames[2] << ", "
1054           << iName << "_params, \"";
1055       printEscapedString(inv->getName());
1056       Out << "\", " << bbname << ");\n";
1057       Out << iName << "->setCallingConv(";
1058       printCallingConv(inv->getCallingConv());
1059       Out << ");";
1060       break;
1061     }
1062     case Instruction::Unwind: {
1063       Out << "  UnwindInst* " << iName << " = new UnwindInst("
1064           << bbname << ");";
1065       break;
1066     }
1067     case Instruction::Unreachable:{
1068       Out << "  UnreachableInst* " << iName << " = new UnreachableInst("
1069           << bbname << ");";
1070       break;
1071     }
1072     case Instruction::Add:
1073     case Instruction::Sub:
1074     case Instruction::Mul:
1075     case Instruction::Div:
1076     case Instruction::Rem:
1077     case Instruction::And:
1078     case Instruction::Or:
1079     case Instruction::Xor:
1080     case Instruction::Shl: 
1081     case Instruction::Shr:{
1082       Out << "  BinaryOperator* "  << iName << " = BinaryOperator::create(";
1083       switch (I->getOpcode()) {
1084         case Instruction::Add: Out << "Instruction::Add"; break;
1085         case Instruction::Sub: Out << "Instruction::Sub"; break;
1086         case Instruction::Mul: Out << "Instruction::Mul"; break;
1087         case Instruction::Div: Out << "Instruction::Div"; break;
1088         case Instruction::Rem: Out << "Instruction::Rem"; break;
1089         case Instruction::And: Out << "Instruction::And"; break;
1090         case Instruction::Or:  Out << "Instruction::Or"; break;
1091         case Instruction::Xor: Out << "Instruction::Xor"; break;
1092         case Instruction::Shl: Out << "Instruction::Shl"; break;
1093         case Instruction::Shr: Out << "Instruction::Shr"; break;
1094         default: Out << "Instruction::BadOpCode"; break;
1095       }
1096       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1097       printEscapedString(I->getName());
1098       Out << "\", " << bbname << ");";
1099       break;
1100     }
1101     case Instruction::SetEQ:
1102     case Instruction::SetNE:
1103     case Instruction::SetLE:
1104     case Instruction::SetGE:
1105     case Instruction::SetLT:
1106     case Instruction::SetGT: {
1107       Out << "  SetCondInst* "  << iName << " = new SetCondInst(";
1108       switch (I->getOpcode()) {
1109         case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1110         case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1111         case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1112         case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1113         case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1114         case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1115         default: Out << "Instruction::BadOpCode"; break;
1116       }
1117       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1118       printEscapedString(I->getName());
1119       Out << "\", " << bbname << ");";
1120       break;
1121     }
1122     case Instruction::Malloc: {
1123       const MallocInst* mallocI = cast<MallocInst>(I);
1124       Out << "  MallocInst* " << iName << " = new MallocInst("
1125           << getCppName(mallocI->getAllocatedType()) << ", ";
1126       if (mallocI->isArrayAllocation())
1127         Out << opNames[0] << ", " ;
1128       Out << "\"";
1129       printEscapedString(mallocI->getName());
1130       Out << "\", " << bbname << ");";
1131       if (mallocI->getAlignment())
1132         Out << "\n  " << iName << "->setAlignment(" 
1133             << mallocI->getAlignment() << ");";
1134       break;
1135     }
1136     case Instruction::Free: {
1137       Out << "  FreeInst* " << iName << " = new FreeInst("
1138           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1139       break;
1140     }
1141     case Instruction::Alloca: {
1142       const AllocaInst* allocaI = cast<AllocaInst>(I);
1143       Out << "  AllocaInst* " << iName << " = new AllocaInst("
1144           << getCppName(allocaI->getAllocatedType()) << ", ";
1145       if (allocaI->isArrayAllocation())
1146         Out << opNames[0] << ", ";
1147       Out << "\"";
1148       printEscapedString(allocaI->getName());
1149       Out << "\", " << bbname << ");";
1150       if (allocaI->getAlignment())
1151         Out << "\n  " << iName << "->setAlignment(" 
1152             << allocaI->getAlignment() << ");";
1153       break;
1154     }
1155     case Instruction::Load:{
1156       const LoadInst* load = cast<LoadInst>(I);
1157       Out << "  LoadInst* " << iName << " = new LoadInst(" 
1158           << opNames[0] << ", \"";
1159       printEscapedString(load->getName());
1160       Out << "\", " << (load->isVolatile() ? "true" : "false" )
1161           << ", " << bbname << ");\n";
1162       break;
1163     }
1164     case Instruction::Store: {
1165       const StoreInst* store = cast<StoreInst>(I);
1166       Out << "  StoreInst* " << iName << " = new StoreInst(" 
1167           << opNames[0] << ", "
1168           << opNames[1] << ", "
1169           << (store->isVolatile() ? "true" : "false") 
1170           << ", " << bbname << ");\n";
1171       break;
1172     }
1173     case Instruction::GetElementPtr: {
1174       const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1175       if (gep->getNumOperands() <= 2) {
1176         Out << "  GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1177             << opNames[0]; 
1178         if (gep->getNumOperands() == 2)
1179           Out << ", " << opNames[1];
1180       } else {
1181         Out << "  std::vector<Value*> " << iName << "_indices;\n";
1182         for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1183           Out << "  " << iName << "_indices.push_back("
1184               << opNames[i] << ");\n";
1185         }
1186         Out << "  Instruction* " << iName << " = new GetElementPtrInst(" 
1187             << opNames[0] << ", " << iName << "_indices";
1188       }
1189       Out << ", \"";
1190       printEscapedString(gep->getName());
1191       Out << "\", " << bbname << ");";
1192       break;
1193     }
1194     case Instruction::PHI: {
1195       const PHINode* phi = cast<PHINode>(I);
1196
1197       Out << "  PHINode* " << iName << " = new PHINode("
1198           << getCppName(phi->getType()) << ", \"";
1199       printEscapedString(phi->getName());
1200       Out << "\", " << bbname << ");\n";
1201       Out << "  " << iName << "->reserveOperandSpace(" 
1202         << phi->getNumIncomingValues()
1203           << ");\n";
1204       for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1205         Out << "  " << iName << "->addIncoming("
1206             << opNames[i] << ", " << opNames[i+1] << ");\n";
1207       }
1208       break;
1209     }
1210     case Instruction::Cast: {
1211       const CastInst* cst = cast<CastInst>(I);
1212       Out << "  CastInst* " << iName << " = new CastInst("
1213           << opNames[0] << ", "
1214           << getCppName(cst->getType()) << ", \"";
1215       printEscapedString(cst->getName());
1216       Out << "\", " << bbname << ");\n";
1217       break;
1218     }
1219     case Instruction::Call:{
1220       const CallInst* call = cast<CallInst>(I);
1221       if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1222         Out << "  InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1223             << getCppName(ila->getFunctionType()) << ", \""
1224             << ila->getAsmString() << "\", \""
1225             << ila->getConstraintString() << "\","
1226             << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1227       }
1228       if (call->getNumOperands() > 3) {
1229         Out << "  std::vector<Value*> " << iName << "_params;\n";
1230         for (unsigned i = 1; i < call->getNumOperands(); ++i) 
1231           Out << "  " << iName << "_params.push_back(" << opNames[i] << ");\n";
1232         Out << "  CallInst* " << iName << " = new CallInst("
1233             << opNames[0] << ", " << iName << "_params, \"";
1234       } else if (call->getNumOperands() == 3) {
1235         Out << "  CallInst* " << iName << " = new CallInst("
1236             << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1237       } else if (call->getNumOperands() == 2) {
1238         Out << "  CallInst* " << iName << " = new CallInst("
1239             << opNames[0] << ", " << opNames[1] << ", \"";
1240       } else {
1241         Out << "  CallInst* " << iName << " = new CallInst(" << opNames[0] 
1242             << ", \"";
1243       }
1244       printEscapedString(call->getName());
1245       Out << "\", " << bbname << ");\n";
1246       Out << "  " << iName << "->setCallingConv(";
1247       printCallingConv(call->getCallingConv());
1248       Out << ");\n";
1249       Out << "  " << iName << "->setTailCall(" 
1250           << (call->isTailCall() ? "true":"false");
1251       Out << ");";
1252       break;
1253     }
1254     case Instruction::Select: {
1255       const SelectInst* sel = cast<SelectInst>(I);
1256       Out << "  SelectInst* " << getCppName(sel) << " = new SelectInst(";
1257       Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1258       printEscapedString(sel->getName());
1259       Out << "\", " << bbname << ");\n";
1260       break;
1261     }
1262     case Instruction::UserOp1:
1263       /// FALL THROUGH
1264     case Instruction::UserOp2: {
1265       /// FIXME: What should be done here?
1266       break;
1267     }
1268     case Instruction::VAArg: {
1269       const VAArgInst* va = cast<VAArgInst>(I);
1270       Out << "  VAArgInst* " << getCppName(va) << " = new VAArgInst("
1271           << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1272       printEscapedString(va->getName());
1273       Out << "\", " << bbname << ");\n";
1274       break;
1275     }
1276     case Instruction::ExtractElement: {
1277       const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1278       Out << "  ExtractElementInst* " << getCppName(eei) 
1279           << " = new ExtractElementInst(" << opNames[0]
1280           << ", " << opNames[1] << ", \"";
1281       printEscapedString(eei->getName());
1282       Out << "\", " << bbname << ");\n";
1283       break;
1284     }
1285     case Instruction::InsertElement: {
1286       const InsertElementInst* iei = cast<InsertElementInst>(I);
1287       Out << "  InsertElementInst* " << getCppName(iei) 
1288           << " = new InsertElementInst(" << opNames[0]
1289           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1290       printEscapedString(iei->getName());
1291       Out << "\", " << bbname << ");\n";
1292       break;
1293     }
1294     case Instruction::ShuffleVector: {
1295       const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1296       Out << "  ShuffleVectorInst* " << getCppName(svi) 
1297           << " = new ShuffleVectorInst(" << opNames[0]
1298           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1299       printEscapedString(svi->getName());
1300       Out << "\", " << bbname << ");\n";
1301       break;
1302     }
1303   }
1304   Out << "\n";
1305   delete [] opNames;
1306 }
1307
1308 }  // end anonymous llvm
1309
1310 namespace llvm {
1311
1312 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1313   o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1314   std::string fname = FuncName.getValue();
1315   if (fname.empty())
1316     fname = "makeLLVMModule";
1317   if (Fragment) {
1318     o << "Module* " << fname << "(Module *mod) {\n";
1319     CppWriter W(o, mod);
1320     W.printFragment();
1321     o << "return mod;\n";
1322     o << "}\n";
1323   } else {
1324     o << "#include <llvm/Module.h>\n";
1325     o << "#include <llvm/DerivedTypes.h>\n";
1326     o << "#include <llvm/Constants.h>\n";
1327     o << "#include <llvm/GlobalVariable.h>\n";
1328     o << "#include <llvm/Function.h>\n";
1329     o << "#include <llvm/CallingConv.h>\n";
1330     o << "#include <llvm/BasicBlock.h>\n";
1331     o << "#include <llvm/Instructions.h>\n";
1332     o << "#include <llvm/InlineAsm.h>\n";
1333     o << "#include <llvm/Pass.h>\n";
1334     o << "#include <llvm/PassManager.h>\n";
1335     o << "#include <llvm/Analysis/Verifier.h>\n";
1336     o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1337     o << "#include <algorithm>\n";
1338     o << "#include <iostream>\n\n";
1339     o << "using namespace llvm;\n\n";
1340     o << "Module* " << fname << "();\n\n";
1341     o << "int main(int argc, char**argv) {\n";
1342     o << "  Module* Mod = makeLLVMModule();\n";
1343     o << "  verifyModule(*Mod, PrintMessageAction);\n";
1344     o << "  std::cerr.flush();\n";
1345     o << "  std::cout.flush();\n";
1346     o << "  PassManager PM;\n";
1347     o << "  PM.add(new PrintModulePass(&std::cout));\n";
1348     o << "  PM.run(*Mod);\n";
1349     o << "  return 0;\n";
1350     o << "}\n\n";
1351     o << "Module* " << fname << "() {\n";
1352     CppWriter W(o, mod);
1353     W.printModule();
1354     o << "return mod;\n";
1355     o << "}\n";
1356   }
1357 }
1358
1359 }