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