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