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