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