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