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