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