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