For PR950:
[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 (const Function* F = dyn_cast<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       const OpaqueType* OT = cast<OpaqueType>(Ty);
540       Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
541       nl(Out);
542       break;
543     }
544     default:
545       error("Invalid TypeID");
546   }
547
548   // If the type had a name, make sure we recreate it.
549   const std::string* progTypeName = 
550     findTypeName(TheModule->getSymbolTable(),Ty);
551   if (progTypeName)
552     Out << "mod->addTypeName(\"" << *progTypeName << "\", " 
553         << typeName << ");";
554     nl(Out);
555
556   // Pop us off the type stack
557   TypeStack.pop_back();
558
559   // Indicate that this type is now defined.
560   DefinedTypes.insert(Ty);
561
562   // Early resolve as many unresolved types as possible. Search the unresolved
563   // types map for the type we just printed. Now that its definition is complete
564   // we can resolve any previous references to it. This prevents a cascade of
565   // unresolved types.
566   TypeMap::iterator I = UnresolvedTypes.find(Ty);
567   if (I != UnresolvedTypes.end()) {
568     Out << "cast<OpaqueType>(" << I->second 
569         << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
570     nl(Out);
571     Out << I->second << " = cast<";
572     switch (Ty->getTypeID()) {
573       case Type::FunctionTyID: Out << "FunctionType"; break;
574       case Type::ArrayTyID:    Out << "ArrayType"; break;
575       case Type::StructTyID:   Out << "StructType"; break;
576       case Type::PackedTyID:   Out << "PackedType"; break;
577       case Type::PointerTyID:  Out << "PointerType"; break;
578       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
579       default:                 Out << "NoSuchDerivedType"; break;
580     }
581     Out << ">(" << I->second << "_fwd.get());";
582     nl(Out); nl(Out);
583     UnresolvedTypes.erase(I);
584   }
585
586   // Finally, separate the type definition from other with a newline.
587   nl(Out);
588
589   // We weren't a recursive type
590   return false;
591 }
592
593 // Prints a type definition. Returns true if it could not resolve all the types
594 // in the definition but had to use a forward reference.
595 void
596 CppWriter::printType(const Type* Ty) {
597   assert(TypeStack.empty());
598   TypeStack.clear();
599   printTypeInternal(Ty);
600   assert(TypeStack.empty());
601 }
602
603 void
604 CppWriter::printTypes(const Module* M) {
605
606   // Walk the symbol table and print out all its types
607   const SymbolTable& symtab = M->getSymbolTable();
608   for (SymbolTable::type_const_iterator TI = symtab.type_begin(), 
609        TE = symtab.type_end(); TI != TE; ++TI) {
610
611     // For primitive types and types already defined, just add a name
612     TypeMap::const_iterator TNI = TypeNames.find(TI->second);
613     if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
614       Out << "mod->addTypeName(\"";
615       printEscapedString(TI->first);
616       Out << "\", " << getCppName(TI->second) << ");";
617       nl(Out);
618     // For everything else, define the type
619     } else {
620       printType(TI->second);
621     }
622   }
623
624   // Add all of the global variables to the value table...
625   for (Module::const_global_iterator I = TheModule->global_begin(), 
626        E = TheModule->global_end(); I != E; ++I) {
627     if (I->hasInitializer())
628       printType(I->getInitializer()->getType());
629     printType(I->getType());
630   }
631
632   // Add all the functions to the table
633   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
634        FI != FE; ++FI) {
635     printType(FI->getReturnType());
636     printType(FI->getFunctionType());
637     // Add all the function arguments
638     for(Function::const_arg_iterator AI = FI->arg_begin(),
639         AE = FI->arg_end(); AI != AE; ++AI) {
640       printType(AI->getType());
641     }
642
643     // Add all of the basic blocks and instructions
644     for (Function::const_iterator BB = FI->begin(),
645          E = FI->end(); BB != E; ++BB) {
646       printType(BB->getType());
647       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 
648            ++I) {
649         printType(I->getType());
650         for (unsigned i = 0; i < I->getNumOperands(); ++i)
651           printType(I->getOperand(i)->getType());
652       }
653     }
654   }
655 }
656
657
658 // printConstant - Print out a constant pool entry...
659 void CppWriter::printConstant(const Constant *CV) {
660   // First, if the constant is actually a GlobalValue (variable or function) or
661   // its already in the constant list then we've printed it already and we can
662   // just return.
663   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
664     return;
665
666   std::string constName(getCppName(CV));
667   std::string typeName(getCppName(CV->getType()));
668   if (CV->isNullValue()) {
669     Out << "Constant* " << constName << " = Constant::getNullValue("
670         << typeName << ");";
671     nl(Out);
672     return;
673   }
674   if (isa<GlobalValue>(CV)) {
675     // Skip variables and functions, we emit them elsewhere
676     return;
677   }
678   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
679     Out << "ConstantBool* " << constName << " = ConstantBool::get(" 
680         << (CB->getValue() ? "true" : "false") << ");";
681   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
682     Out << "ConstantInt* " << constName << " = ConstantInt::get(" 
683         << typeName << ", " 
684         << (CV->getType()->isSigned() ? CI->getSExtValue() : CI->getZExtValue())
685         << ");";
686   } else if (isa<ConstantAggregateZero>(CV)) {
687     Out << "ConstantAggregateZero* " << constName 
688         << " = ConstantAggregateZero::get(" << typeName << ");";
689   } else if (isa<ConstantPointerNull>(CV)) {
690     Out << "ConstantPointerNull* " << constName 
691         << " = ConstanPointerNull::get(" << typeName << ");";
692   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
693     Out << "ConstantFP* " << constName << " = ";
694     printCFP(CFP);
695     Out << ";";
696   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
697     if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
698       Out << "Constant* " << constName << " = ConstantArray::get(\"";
699       printEscapedString(CA->getAsString());
700       // Determine if we want null termination or not.
701       if (CA->getType()->getNumElements() <= CA->getAsString().length())
702         Out << "\", false";// No null terminator
703       else
704         Out << "\", true"; // Indicate that the null terminator should be added.
705       Out << ");";
706     } else { 
707       Out << "std::vector<Constant*> " << constName << "_elems;";
708       nl(Out);
709       unsigned N = CA->getNumOperands();
710       for (unsigned i = 0; i < N; ++i) {
711         printConstant(CA->getOperand(i)); // recurse to print operands
712         Out << constName << "_elems.push_back("
713             << getCppName(CA->getOperand(i)) << ");";
714         nl(Out);
715       }
716       Out << "Constant* " << constName << " = ConstantArray::get(" 
717           << typeName << ", " << constName << "_elems);";
718     }
719   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
720     Out << "std::vector<Constant*> " << constName << "_fields;";
721     nl(Out);
722     unsigned N = CS->getNumOperands();
723     for (unsigned i = 0; i < N; i++) {
724       printConstant(CS->getOperand(i));
725       Out << constName << "_fields.push_back("
726           << getCppName(CS->getOperand(i)) << ");";
727       nl(Out);
728     }
729     Out << "Constant* " << constName << " = ConstantStruct::get(" 
730         << typeName << ", " << constName << "_fields);";
731   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
732     Out << "std::vector<Constant*> " << constName << "_elems;";
733     nl(Out);
734     unsigned N = CP->getNumOperands();
735     for (unsigned i = 0; i < N; ++i) {
736       printConstant(CP->getOperand(i));
737       Out << constName << "_elems.push_back("
738           << getCppName(CP->getOperand(i)) << ");";
739       nl(Out);
740     }
741     Out << "Constant* " << constName << " = ConstantPacked::get(" 
742         << typeName << ", " << constName << "_elems);";
743   } else if (isa<UndefValue>(CV)) {
744     Out << "UndefValue* " << constName << " = UndefValue::get(" 
745         << typeName << ");";
746   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
747     if (CE->getOpcode() == Instruction::GetElementPtr) {
748       Out << "std::vector<Constant*> " << constName << "_indices;";
749       nl(Out);
750       printConstant(CE->getOperand(0));
751       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
752         printConstant(CE->getOperand(i));
753         Out << constName << "_indices.push_back("
754             << getCppName(CE->getOperand(i)) << ");";
755         nl(Out);
756       }
757       Out << "Constant* " << constName 
758           << " = ConstantExpr::getGetElementPtr(" 
759           << getCppName(CE->getOperand(0)) << ", " 
760           << constName << "_indices);";
761     } else if (CE->getOpcode() == Instruction::Cast) {
762       printConstant(CE->getOperand(0));
763       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
764       Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
765           << ");";
766     } else {
767       unsigned N = CE->getNumOperands();
768       for (unsigned i = 0; i < N; ++i ) {
769         printConstant(CE->getOperand(i));
770       }
771       Out << "Constant* " << constName << " = ConstantExpr::";
772       switch (CE->getOpcode()) {
773         case Instruction::Add:    Out << "getAdd";  break;
774         case Instruction::Sub:    Out << "getSub"; break;
775         case Instruction::Mul:    Out << "getMul"; break;
776         case Instruction::Div:    Out << "getDiv"; break;
777         case Instruction::Rem:    Out << "getRem"; break;
778         case Instruction::And:    Out << "getAnd"; break;
779         case Instruction::Or:     Out << "getOr"; break;
780         case Instruction::Xor:    Out << "getXor"; break;
781         case Instruction::SetEQ:  Out << "getSetEQ"; break;
782         case Instruction::SetNE:  Out << "getSetNE"; break;
783         case Instruction::SetLE:  Out << "getSetLE"; break;
784         case Instruction::SetGE:  Out << "getSetGE"; break;
785         case Instruction::SetLT:  Out << "getSetLT"; break;
786         case Instruction::SetGT:  Out << "getSetGT"; break;
787         case Instruction::Shl:    Out << "getShl"; break;
788         case Instruction::Shr:    Out << "getShr"; break;
789         case Instruction::Select: Out << "getSelect"; break;
790         case Instruction::ExtractElement: Out << "getExtractElement"; break;
791         case Instruction::InsertElement:  Out << "getInsertElement"; break;
792         case Instruction::ShuffleVector:  Out << "getShuffleVector"; break;
793         default:
794           error("Invalid constant expression");
795           break;
796       }
797       Out << getCppName(CE->getOperand(0));
798       for (unsigned i = 1; i < CE->getNumOperands(); ++i) 
799         Out << ", " << getCppName(CE->getOperand(i));
800       Out << ");";
801     }
802   } else {
803     error("Bad Constant");
804     Out << "Constant* " << constName << " = 0; ";
805   }
806   nl(Out);
807 }
808
809 void
810 CppWriter::printConstants(const Module* M) {
811   // Traverse all the global variables looking for constant initializers
812   for (Module::const_global_iterator I = TheModule->global_begin(), 
813        E = TheModule->global_end(); I != E; ++I)
814     if (I->hasInitializer())
815       printConstant(I->getInitializer());
816
817   // Traverse the LLVM functions looking for constants
818   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
819        FI != FE; ++FI) {
820     // Add all of the basic blocks and instructions
821     for (Function::const_iterator BB = FI->begin(),
822          E = FI->end(); BB != E; ++BB) {
823       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 
824            ++I) {
825         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
826           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
827             printConstant(C);
828           }
829         }
830       }
831     }
832   }
833 }
834
835 void CppWriter::printVariableUses(const GlobalVariable *GV) {
836   nl(Out) << "// Type Definitions";
837   nl(Out);
838   printType(GV->getType());
839   if (GV->hasInitializer()) {
840     Constant* Init = GV->getInitializer();
841     printType(Init->getType());
842     if (Function* F = dyn_cast<Function>(Init)) {
843       nl(Out)<< "/ Function Declarations"; nl(Out);
844       printFunctionHead(F);
845     } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
846       nl(Out) << "// Global Variable Declarations"; nl(Out);
847       printVariableHead(gv);
848     } else  {
849       nl(Out) << "// Constant Definitions"; nl(Out);
850       printConstant(gv);
851     }
852     if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
853       nl(Out) << "// Global Variable Definitions"; nl(Out);
854       printVariableBody(gv);
855     }
856   }
857 }
858
859 void CppWriter::printVariableHead(const GlobalVariable *GV) {
860   nl(Out) << "GlobalVariable* " << getCppName(GV);
861   if (is_inline) {
862      Out << " = mod->getGlobalVariable(";
863      printEscapedString(GV->getName());
864      Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
865      nl(Out) << "if (!" << getCppName(GV) << ") {";
866      in(); nl(Out) << getCppName(GV);
867   }
868   Out << " = new GlobalVariable(";
869   nl(Out) << "/*Type=*/";
870   printCppName(GV->getType()->getElementType());
871   Out << ",";
872   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
873   Out << ",";
874   nl(Out) << "/*Linkage=*/";
875   printLinkageType(GV->getLinkage());
876   Out << ",";
877   nl(Out) << "/*Initializer=*/0, ";
878   if (GV->hasInitializer()) {
879     Out << "// has initializer, specified below";
880   }
881   nl(Out) << "/*Name=*/\"";
882   printEscapedString(GV->getName());
883   Out << "\",";
884   nl(Out) << "mod);";
885   nl(Out);
886
887   if (GV->hasSection()) {
888     printCppName(GV);
889     Out << "->setSection(\"";
890     printEscapedString(GV->getSection());
891     Out << "\");";
892     nl(Out);
893   }
894   if (GV->getAlignment()) {
895     printCppName(GV);
896     Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
897     nl(Out);
898   };
899   if (is_inline) {
900     out(); Out << "}"; nl(Out);
901   }
902 }
903
904 void 
905 CppWriter::printVariableBody(const GlobalVariable *GV) {
906   if (GV->hasInitializer()) {
907     printCppName(GV);
908     Out << "->setInitializer(";
909     //if (!isa<GlobalValue(GV->getInitializer()))
910     //else 
911       Out << getCppName(GV->getInitializer()) << ");";
912       nl(Out);
913   }
914 }
915
916 std::string
917 CppWriter::getOpName(Value* V) {
918   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
919     return getCppName(V);
920
921   // See if its alread in the map of forward references, if so just return the
922   // name we already set up for it
923   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
924   if (I != ForwardRefs.end())
925     return I->second;
926
927   // This is a new forward reference. Generate a unique name for it
928   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
929
930   // Yes, this is a hack. An Argument is the smallest instantiable value that
931   // we can make as a placeholder for the real value. We'll replace these
932   // Argument instances later.
933   Out << "Argument* " << result << " = new Argument(" 
934       << getCppName(V->getType()) << ");";
935   nl(Out);
936   ForwardRefs[V] = result;
937   return result;
938 }
939
940 // printInstruction - This member is called for each Instruction in a function.
941 void 
942 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
943   std::string iName(getCppName(I));
944
945   // Before we emit this instruction, we need to take care of generating any
946   // forward references. So, we get the names of all the operands in advance
947   std::string* opNames = new std::string[I->getNumOperands()];
948   for (unsigned i = 0; i < I->getNumOperands(); i++) {
949     opNames[i] = getOpName(I->getOperand(i));
950   }
951
952   switch (I->getOpcode()) {
953     case Instruction::Ret: {
954       const ReturnInst* ret =  cast<ReturnInst>(I);
955       Out << "ReturnInst* " << iName << " = new ReturnInst("
956           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
957       break;
958     }
959     case Instruction::Br: {
960       const BranchInst* br = cast<BranchInst>(I);
961       Out << "BranchInst* " << iName << " = new BranchInst(" ;
962       if (br->getNumOperands() == 3 ) {
963         Out << opNames[0] << ", " 
964             << opNames[1] << ", "
965             << opNames[2] << ", ";
966
967       } else if (br->getNumOperands() == 1) {
968         Out << opNames[0] << ", ";
969       } else {
970         error("Branch with 2 operands?");
971       }
972       Out << bbname << ");";
973       break;
974     }
975     case Instruction::Switch: {
976       const SwitchInst* sw = cast<SwitchInst>(I);
977       Out << "SwitchInst* " << iName << " = new SwitchInst("
978           << opNames[0] << ", "
979           << opNames[1] << ", "
980           << sw->getNumCases() << ", " << bbname << ");";
981       nl(Out);
982       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
983         Out << iName << "->addCase(" 
984             << opNames[i] << ", "
985             << opNames[i+1] << ");";
986         nl(Out);
987       }
988       break;
989     }
990     case Instruction::Invoke: {
991       const InvokeInst* inv = cast<InvokeInst>(I);
992       Out << "std::vector<Value*> " << iName << "_params;";
993       nl(Out);
994       for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
995         Out << iName << "_params.push_back("
996             << opNames[i] << ");";
997         nl(Out);
998       }
999       Out << "InvokeInst* " << iName << " = new InvokeInst("
1000           << opNames[0] << ", "
1001           << opNames[1] << ", "
1002           << opNames[2] << ", "
1003           << iName << "_params, \"";
1004       printEscapedString(inv->getName());
1005       Out << "\", " << bbname << ");";
1006       nl(Out) << iName << "->setCallingConv(";
1007       printCallingConv(inv->getCallingConv());
1008       Out << ");";
1009       break;
1010     }
1011     case Instruction::Unwind: {
1012       Out << "UnwindInst* " << iName << " = new UnwindInst("
1013           << bbname << ");";
1014       break;
1015     }
1016     case Instruction::Unreachable:{
1017       Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1018           << bbname << ");";
1019       break;
1020     }
1021     case Instruction::Add:
1022     case Instruction::Sub:
1023     case Instruction::Mul:
1024     case Instruction::Div:
1025     case Instruction::Rem:
1026     case Instruction::And:
1027     case Instruction::Or:
1028     case Instruction::Xor:
1029     case Instruction::Shl: 
1030     case Instruction::Shr:{
1031       Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1032       switch (I->getOpcode()) {
1033         case Instruction::Add: Out << "Instruction::Add"; break;
1034         case Instruction::Sub: Out << "Instruction::Sub"; break;
1035         case Instruction::Mul: Out << "Instruction::Mul"; break;
1036         case Instruction::Div: Out << "Instruction::Div"; break;
1037         case Instruction::Rem: Out << "Instruction::Rem"; break;
1038         case Instruction::And: Out << "Instruction::And"; break;
1039         case Instruction::Or:  Out << "Instruction::Or";  break;
1040         case Instruction::Xor: Out << "Instruction::Xor"; break;
1041         case Instruction::Shl: Out << "Instruction::Shl"; break;
1042         case Instruction::Shr: Out << "Instruction::Shr"; break;
1043         default: Out << "Instruction::BadOpCode"; break;
1044       }
1045       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1046       printEscapedString(I->getName());
1047       Out << "\", " << bbname << ");";
1048       break;
1049     }
1050     case Instruction::SetEQ:
1051     case Instruction::SetNE:
1052     case Instruction::SetLE:
1053     case Instruction::SetGE:
1054     case Instruction::SetLT:
1055     case Instruction::SetGT: {
1056       Out << "SetCondInst* " << iName << " = new SetCondInst(";
1057       switch (I->getOpcode()) {
1058         case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1059         case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1060         case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1061         case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1062         case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1063         case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1064         default: Out << "Instruction::BadOpCode"; break;
1065       }
1066       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1067       printEscapedString(I->getName());
1068       Out << "\", " << bbname << ");";
1069       break;
1070     }
1071     case Instruction::Malloc: {
1072       const MallocInst* mallocI = cast<MallocInst>(I);
1073       Out << "MallocInst* " << iName << " = new MallocInst("
1074           << getCppName(mallocI->getAllocatedType()) << ", ";
1075       if (mallocI->isArrayAllocation())
1076         Out << opNames[0] << ", " ;
1077       Out << "\"";
1078       printEscapedString(mallocI->getName());
1079       Out << "\", " << bbname << ");";
1080       if (mallocI->getAlignment())
1081         nl(Out) << iName << "->setAlignment(" 
1082             << mallocI->getAlignment() << ");";
1083       break;
1084     }
1085     case Instruction::Free: {
1086       Out << "FreeInst* " << iName << " = new FreeInst("
1087           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1088       break;
1089     }
1090     case Instruction::Alloca: {
1091       const AllocaInst* allocaI = cast<AllocaInst>(I);
1092       Out << "AllocaInst* " << iName << " = new AllocaInst("
1093           << getCppName(allocaI->getAllocatedType()) << ", ";
1094       if (allocaI->isArrayAllocation())
1095         Out << opNames[0] << ", ";
1096       Out << "\"";
1097       printEscapedString(allocaI->getName());
1098       Out << "\", " << bbname << ");";
1099       if (allocaI->getAlignment())
1100         nl(Out) << iName << "->setAlignment(" 
1101             << allocaI->getAlignment() << ");";
1102       break;
1103     }
1104     case Instruction::Load:{
1105       const LoadInst* load = cast<LoadInst>(I);
1106       Out << "LoadInst* " << iName << " = new LoadInst(" 
1107           << opNames[0] << ", \"";
1108       printEscapedString(load->getName());
1109       Out << "\", " << (load->isVolatile() ? "true" : "false" )
1110           << ", " << bbname << ");";
1111       break;
1112     }
1113     case Instruction::Store: {
1114       const StoreInst* store = cast<StoreInst>(I);
1115       Out << "StoreInst* " << iName << " = new StoreInst(" 
1116           << opNames[0] << ", "
1117           << opNames[1] << ", "
1118           << (store->isVolatile() ? "true" : "false") 
1119           << ", " << bbname << ");";
1120       break;
1121     }
1122     case Instruction::GetElementPtr: {
1123       const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1124       if (gep->getNumOperands() <= 2) {
1125         Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1126             << opNames[0]; 
1127         if (gep->getNumOperands() == 2)
1128           Out << ", " << opNames[1];
1129       } else {
1130         Out << "std::vector<Value*> " << iName << "_indices;";
1131         nl(Out);
1132         for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1133           Out << iName << "_indices.push_back("
1134               << opNames[i] << ");";
1135           nl(Out);
1136         }
1137         Out << "Instruction* " << iName << " = new GetElementPtrInst(" 
1138             << opNames[0] << ", " << iName << "_indices";
1139       }
1140       Out << ", \"";
1141       printEscapedString(gep->getName());
1142       Out << "\", " << bbname << ");";
1143       break;
1144     }
1145     case Instruction::PHI: {
1146       const PHINode* phi = cast<PHINode>(I);
1147
1148       Out << "PHINode* " << iName << " = new PHINode("
1149           << getCppName(phi->getType()) << ", \"";
1150       printEscapedString(phi->getName());
1151       Out << "\", " << bbname << ");";
1152       nl(Out) << iName << "->reserveOperandSpace(" 
1153         << phi->getNumIncomingValues()
1154           << ");";
1155       nl(Out);
1156       for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1157         Out << iName << "->addIncoming("
1158             << opNames[i] << ", " << opNames[i+1] << ");";
1159         nl(Out);
1160       }
1161       break;
1162     }
1163     case Instruction::Cast: {
1164       const CastInst* cst = cast<CastInst>(I);
1165       Out << "CastInst* " << iName << " = new CastInst("
1166           << opNames[0] << ", "
1167           << getCppName(cst->getType()) << ", \"";
1168       printEscapedString(cst->getName());
1169       Out << "\", " << bbname << ");";
1170       break;
1171     }
1172     case Instruction::Call:{
1173       const CallInst* call = cast<CallInst>(I);
1174       if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1175         Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1176             << getCppName(ila->getFunctionType()) << ", \""
1177             << ila->getAsmString() << "\", \""
1178             << ila->getConstraintString() << "\","
1179             << (ila->hasSideEffects() ? "true" : "false") << ");";
1180         nl(Out);
1181       }
1182       if (call->getNumOperands() > 3) {
1183         Out << "std::vector<Value*> " << iName << "_params;";
1184         nl(Out);
1185         for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1186           Out << iName << "_params.push_back(" << opNames[i] << ");";
1187           nl(Out);
1188         }
1189         Out << "CallInst* " << iName << " = new CallInst("
1190             << opNames[0] << ", " << iName << "_params, \"";
1191       } else if (call->getNumOperands() == 3) {
1192         Out << "CallInst* " << iName << " = new CallInst("
1193             << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1194       } else if (call->getNumOperands() == 2) {
1195         Out << "CallInst* " << iName << " = new CallInst("
1196             << opNames[0] << ", " << opNames[1] << ", \"";
1197       } else {
1198         Out << "CallInst* " << iName << " = new CallInst(" << opNames[0] 
1199             << ", \"";
1200       }
1201       printEscapedString(call->getName());
1202       Out << "\", " << bbname << ");";
1203       nl(Out) << iName << "->setCallingConv(";
1204       printCallingConv(call->getCallingConv());
1205       Out << ");";
1206       nl(Out) << iName << "->setTailCall(" 
1207           << (call->isTailCall() ? "true":"false");
1208       Out << ");";
1209       break;
1210     }
1211     case Instruction::Select: {
1212       const SelectInst* sel = cast<SelectInst>(I);
1213       Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1214       Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1215       printEscapedString(sel->getName());
1216       Out << "\", " << bbname << ");";
1217       break;
1218     }
1219     case Instruction::UserOp1:
1220       /// FALL THROUGH
1221     case Instruction::UserOp2: {
1222       /// FIXME: What should be done here?
1223       break;
1224     }
1225     case Instruction::VAArg: {
1226       const VAArgInst* va = cast<VAArgInst>(I);
1227       Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1228           << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1229       printEscapedString(va->getName());
1230       Out << "\", " << bbname << ");";
1231       break;
1232     }
1233     case Instruction::ExtractElement: {
1234       const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1235       Out << "ExtractElementInst* " << getCppName(eei) 
1236           << " = new ExtractElementInst(" << opNames[0]
1237           << ", " << opNames[1] << ", \"";
1238       printEscapedString(eei->getName());
1239       Out << "\", " << bbname << ");";
1240       break;
1241     }
1242     case Instruction::InsertElement: {
1243       const InsertElementInst* iei = cast<InsertElementInst>(I);
1244       Out << "InsertElementInst* " << getCppName(iei) 
1245           << " = new InsertElementInst(" << opNames[0]
1246           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1247       printEscapedString(iei->getName());
1248       Out << "\", " << bbname << ");";
1249       break;
1250     }
1251     case Instruction::ShuffleVector: {
1252       const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1253       Out << "ShuffleVectorInst* " << getCppName(svi) 
1254           << " = new ShuffleVectorInst(" << opNames[0]
1255           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1256       printEscapedString(svi->getName());
1257       Out << "\", " << bbname << ");";
1258       break;
1259     }
1260   }
1261   DefinedValues.insert(I);
1262   nl(Out);
1263   delete [] opNames;
1264 }
1265
1266 // Print out the types, constants and declarations needed by one function
1267 void CppWriter::printFunctionUses(const Function* F) {
1268
1269   nl(Out) << "// Type Definitions"; nl(Out);
1270   if (!is_inline) {
1271     // Print the function's return type
1272     printType(F->getReturnType());
1273
1274     // Print the function's function type
1275     printType(F->getFunctionType());
1276
1277     // Print the types of each of the function's arguments
1278     for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 
1279         AI != AE; ++AI) {
1280       printType(AI->getType());
1281     }
1282   }
1283
1284   // Print type definitions for every type referenced by an instruction and
1285   // make a note of any global values or constants that are referenced
1286   std::vector<GlobalValue*> gvs;
1287   std::vector<Constant*> consts;
1288   for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1289     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 
1290          I != E; ++I) {
1291       // Print the type of the instruction itself
1292       printType(I->getType());
1293
1294       // Print the type of each of the instruction's operands
1295       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1296         Value* operand = I->getOperand(i);
1297         printType(operand->getType());
1298         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1299           gvs.push_back(GV);
1300         else if (Constant* C = dyn_cast<Constant>(operand))
1301           consts.push_back(C);
1302       }
1303     }
1304   }
1305
1306   // Print the function declarations for any functions encountered
1307   nl(Out) << "// Function Declarations"; nl(Out);
1308   for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1309        I != E; ++I) {
1310     if (Function* Fun = dyn_cast<Function>(*I)) {
1311       if (!is_inline || Fun != F)
1312         printFunctionHead(Fun);
1313     }
1314   }
1315
1316   // Print the global variable declarations for any variables encountered
1317   nl(Out) << "// Global Variable Declarations"; nl(Out);
1318   for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1319        I != E; ++I) {
1320     if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1321       printVariableHead(F);
1322   }
1323
1324   // Print the constants found
1325   nl(Out) << "// Constant Definitions"; nl(Out);
1326   for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1327        I != E; ++I) {
1328       printConstant(*I);
1329   }
1330
1331   // Process the global variables definitions now that all the constants have
1332   // been emitted. These definitions just couple the gvars with their constant
1333   // initializers.
1334   nl(Out) << "// Global Variable Definitions"; nl(Out);
1335   for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1336        I != E; ++I) {
1337     if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1338       printVariableBody(GV);
1339   }
1340 }
1341
1342 void CppWriter::printFunctionHead(const Function* F) {
1343   nl(Out) << "Function* " << getCppName(F); 
1344   if (is_inline) {
1345     Out << " = mod->getFunction(\"";
1346     printEscapedString(F->getName());
1347     Out << "\", " << getCppName(F->getFunctionType()) << ");";
1348     nl(Out) << "if (!" << getCppName(F) << ") {";
1349     nl(Out) << getCppName(F);
1350   }
1351   Out<< " = new Function(";
1352   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1353   nl(Out) << "/*Linkage=*/";
1354   printLinkageType(F->getLinkage());
1355   Out << ",";
1356   nl(Out) << "/*Name=*/\"";
1357   printEscapedString(F->getName());
1358   Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1359   nl(Out,-1);
1360   printCppName(F);
1361   Out << "->setCallingConv(";
1362   printCallingConv(F->getCallingConv());
1363   Out << ");";
1364   nl(Out);
1365   if (F->hasSection()) {
1366     printCppName(F);
1367     Out << "->setSection(\"" << F->getSection() << "\");";
1368     nl(Out);
1369   }
1370   if (F->getAlignment()) {
1371     printCppName(F);
1372     Out << "->setAlignment(" << F->getAlignment() << ");";
1373     nl(Out);
1374   }
1375   if (is_inline) {
1376     Out << "}";
1377     nl(Out);
1378   }
1379 }
1380
1381 void CppWriter::printFunctionBody(const Function *F) {
1382   if (F->isExternal())
1383     return; // external functions have no bodies.
1384
1385   // Clear the DefinedValues and ForwardRefs maps because we can't have 
1386   // cross-function forward refs
1387   ForwardRefs.clear();
1388   DefinedValues.clear();
1389
1390   // Create all the argument values
1391   if (!is_inline) {
1392     if (!F->arg_empty()) {
1393       Out << "Function::arg_iterator args = " << getCppName(F) 
1394           << "->arg_begin();";
1395       nl(Out);
1396     }
1397     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1398          AI != AE; ++AI) {
1399       Out << "Value* " << getCppName(AI) << " = args++;";
1400       nl(Out);
1401       if (AI->hasName()) {
1402         Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1403         nl(Out);
1404       }
1405     }
1406   }
1407
1408   // Create all the basic blocks
1409   nl(Out);
1410   for (Function::const_iterator BI = F->begin(), BE = F->end(); 
1411        BI != BE; ++BI) {
1412     std::string bbname(getCppName(BI));
1413     Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1414     if (BI->hasName())
1415       printEscapedString(BI->getName());
1416     Out << "\"," << getCppName(BI->getParent()) << ",0);";
1417     nl(Out);
1418   }
1419
1420   // Output all of its basic blocks... for the function
1421   for (Function::const_iterator BI = F->begin(), BE = F->end(); 
1422        BI != BE; ++BI) {
1423     std::string bbname(getCppName(BI));
1424     nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1425     nl(Out);
1426
1427     // Output all of the instructions in the basic block...
1428     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); 
1429          I != E; ++I) {
1430       printInstruction(I,bbname);
1431     }
1432   }
1433
1434   // Loop over the ForwardRefs and resolve them now that all instructions
1435   // are generated.
1436   if (!ForwardRefs.empty()) {
1437     nl(Out) << "// Resolve Forward References";
1438     nl(Out);
1439   }
1440   
1441   while (!ForwardRefs.empty()) {
1442     ForwardRefMap::iterator I = ForwardRefs.begin();
1443     Out << I->second << "->replaceAllUsesWith(" 
1444         << getCppName(I->first) << "); delete " << I->second << ";";
1445     nl(Out);
1446     ForwardRefs.erase(I);
1447   }
1448 }
1449
1450 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1451   const Function* F = TheModule->getNamedFunction(func);
1452   if (!F) {
1453     error(std::string("Function '") + func + "' not found in input module");
1454     return;
1455   }
1456   if (F->isExternal()) {
1457     error(std::string("Function '") + func + "' is external!");
1458     return;
1459   }
1460   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *" 
1461       << getCppName(F);
1462   unsigned arg_count = 1;
1463   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1464        AI != AE; ++AI) {
1465     Out << ", Value* arg_" << arg_count;
1466   }
1467   Out << ") {";
1468   nl(Out);
1469   is_inline = true;
1470   printFunctionUses(F);
1471   printFunctionBody(F);
1472   is_inline = false;
1473   Out << "return " << getCppName(F->begin()) << ";";
1474   nl(Out) << "}";
1475   nl(Out);
1476 }
1477
1478 void CppWriter::printModuleBody() {
1479   // Print out all the type definitions
1480   nl(Out) << "// Type Definitions"; nl(Out);
1481   printTypes(TheModule);
1482
1483   // Functions can call each other and global variables can reference them so 
1484   // define all the functions first before emitting their function bodies.
1485   nl(Out) << "// Function Declarations"; nl(Out);
1486   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 
1487        I != E; ++I)
1488     printFunctionHead(I);
1489
1490   // Process the global variables declarations. We can't initialze them until
1491   // after the constants are printed so just print a header for each global
1492   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1493   for (Module::const_global_iterator I = TheModule->global_begin(), 
1494        E = TheModule->global_end(); I != E; ++I) {
1495     printVariableHead(I);
1496   }
1497
1498   // Print out all the constants definitions. Constants don't recurse except
1499   // through GlobalValues. All GlobalValues have been declared at this point
1500   // so we can proceed to generate the constants.
1501   nl(Out) << "// Constant Definitions"; nl(Out);
1502   printConstants(TheModule);
1503
1504   // Process the global variables definitions now that all the constants have
1505   // been emitted. These definitions just couple the gvars with their constant
1506   // initializers.
1507   nl(Out) << "// Global Variable Definitions"; nl(Out);
1508   for (Module::const_global_iterator I = TheModule->global_begin(), 
1509        E = TheModule->global_end(); I != E; ++I) {
1510     printVariableBody(I);
1511   }
1512
1513   // Finally, we can safely put out all of the function bodies.
1514   nl(Out) << "// Function Definitions"; nl(Out);
1515   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 
1516        I != E; ++I) {
1517     if (!I->isExternal()) {
1518       nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I) 
1519           << ")";
1520       nl(Out) << "{";
1521       nl(Out,1);
1522       printFunctionBody(I);
1523       nl(Out,-1) << "}";
1524       nl(Out);
1525     }
1526   }
1527 }
1528
1529 void CppWriter::printProgram(
1530   const std::string& fname, 
1531   const std::string& mName
1532 ) {
1533   Out << "#include <llvm/Module.h>\n";
1534   Out << "#include <llvm/DerivedTypes.h>\n";
1535   Out << "#include <llvm/Constants.h>\n";
1536   Out << "#include <llvm/GlobalVariable.h>\n";
1537   Out << "#include <llvm/Function.h>\n";
1538   Out << "#include <llvm/CallingConv.h>\n";
1539   Out << "#include <llvm/BasicBlock.h>\n";
1540   Out << "#include <llvm/Instructions.h>\n";
1541   Out << "#include <llvm/InlineAsm.h>\n";
1542   Out << "#include <llvm/Support/MathExtras.h>\n";
1543   Out << "#include <llvm/Pass.h>\n";
1544   Out << "#include <llvm/PassManager.h>\n";
1545   Out << "#include <llvm/Analysis/Verifier.h>\n";
1546   Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1547   Out << "#include <algorithm>\n";
1548   Out << "#include <iostream>\n\n";
1549   Out << "using namespace llvm;\n\n";
1550   Out << "Module* " << fname << "();\n\n";
1551   Out << "int main(int argc, char**argv) {\n";
1552   Out << "  Module* Mod = makeLLVMModule();\n";
1553   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1554   Out << "  std::cerr.flush();\n";
1555   Out << "  std::cout.flush();\n";
1556   Out << "  PassManager PM;\n";
1557   Out << "  PM.add(new PrintModulePass(&std::cout));\n";
1558   Out << "  PM.run(*Mod);\n";
1559   Out << "  return 0;\n";
1560   Out << "}\n\n";
1561   printModule(fname,mName);
1562 }
1563
1564 void CppWriter::printModule(
1565   const std::string& fname, 
1566   const std::string& mName
1567 ) {
1568   nl(Out) << "Module* " << fname << "() {";
1569   nl(Out,1) << "// Module Construction";
1570   nl(Out) << "Module* mod = new Module(\"" << mName << "\");"; 
1571   nl(Out) << "mod->setEndianness(";
1572   switch (TheModule->getEndianness()) {
1573     case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1574     case Module::BigEndian:    Out << "Module::BigEndian);";    break;
1575     case Module::AnyEndianness:Out << "Module::AnyEndianness);";  break;
1576   }
1577   nl(Out) << "mod->setPointerSize(";
1578   switch (TheModule->getPointerSize()) {
1579     case Module::Pointer32:      Out << "Module::Pointer32);"; break;
1580     case Module::Pointer64:      Out << "Module::Pointer64);"; break;
1581     case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1582   }
1583   nl(Out);
1584   if (!TheModule->getTargetTriple().empty()) {
1585     Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() 
1586         << "\");";
1587     nl(Out);
1588   }
1589
1590   if (!TheModule->getModuleInlineAsm().empty()) {
1591     Out << "mod->setModuleInlineAsm(\"";
1592     printEscapedString(TheModule->getModuleInlineAsm());
1593     Out << "\");";
1594     nl(Out);
1595   }
1596   
1597   // Loop over the dependent libraries and emit them.
1598   Module::lib_iterator LI = TheModule->lib_begin();
1599   Module::lib_iterator LE = TheModule->lib_end();
1600   while (LI != LE) {
1601     Out << "mod->addLibrary(\"" << *LI << "\");";
1602     nl(Out);
1603     ++LI;
1604   }
1605   printModuleBody();
1606   nl(Out) << "return mod;";
1607   nl(Out,-1) << "}";
1608   nl(Out);
1609 }
1610
1611 void CppWriter::printContents(
1612   const std::string& fname, // Name of generated function
1613   const std::string& mName // Name of module generated module
1614 ) {
1615   Out << "\nModule* " << fname << "(Module *mod) {\n";
1616   Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1617   printModuleBody();
1618   Out << "\nreturn mod;\n";
1619   Out << "\n}\n";
1620 }
1621
1622 void CppWriter::printFunction(
1623   const std::string& fname, // Name of generated function
1624   const std::string& funcName // Name of function to generate
1625 ) {
1626   const Function* F = TheModule->getNamedFunction(funcName);
1627   if (!F) {
1628     error(std::string("Function '") + funcName + "' not found in input module");
1629     return;
1630   }
1631   Out << "\nFunction* " << fname << "(Module *mod) {\n";
1632   printFunctionUses(F);
1633   printFunctionHead(F);
1634   printFunctionBody(F);
1635   Out << "return " << getCppName(F) << ";\n";
1636   Out << "}\n";
1637 }
1638
1639 void CppWriter::printVariable(
1640   const std::string& fname,  /// Name of generated function
1641   const std::string& varName // Name of variable to generate
1642 ) {
1643   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1644
1645   if (!GV) {
1646     error(std::string("Variable '") + varName + "' not found in input module");
1647     return;
1648   }
1649   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1650   printVariableUses(GV);
1651   printVariableHead(GV);
1652   printVariableBody(GV);
1653   Out << "return " << getCppName(GV) << ";\n";
1654   Out << "}\n";
1655 }
1656
1657 void CppWriter::printType(
1658   const std::string& fname,  /// Name of generated function
1659   const std::string& typeName // Name of type to generate
1660 ) {
1661   const Type* Ty = TheModule->getTypeByName(typeName);
1662   if (!Ty) {
1663     error(std::string("Type '") + typeName + "' not found in input module");
1664     return;
1665   }
1666   Out << "\nType* " << fname << "(Module *mod) {\n";
1667   printType(Ty);
1668   Out << "return " << getCppName(Ty) << ";\n";
1669   Out << "}\n";
1670 }
1671
1672 }  // end anonymous llvm
1673
1674 namespace llvm {
1675
1676 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1677   // Initialize a CppWriter for us to use
1678   CppWriter W(o, mod);
1679
1680   // Emit a header
1681   o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1682
1683   // Get the name of the function we're supposed to generate
1684   std::string fname = FuncName.getValue();
1685
1686   // Get the name of the thing we are to generate
1687   std::string tgtname = NameToGenerate.getValue();
1688   if (GenerationType == GenModule || 
1689       GenerationType == GenContents || 
1690       GenerationType == GenProgram) {
1691     if (tgtname == "!bad!") {
1692       if (mod->getModuleIdentifier() == "-")
1693         tgtname = "<stdin>";
1694       else
1695         tgtname = mod->getModuleIdentifier();
1696     }
1697   } else if (tgtname == "!bad!") {
1698     W.error("You must use the -for option with -gen-{function,variable,type}");
1699   }
1700
1701   switch (WhatToGenerate(GenerationType)) {
1702     case GenProgram:
1703       if (fname.empty())
1704         fname = "makeLLVMModule";
1705       W.printProgram(fname,tgtname);
1706       break;
1707     case GenModule:
1708       if (fname.empty())
1709         fname = "makeLLVMModule";
1710       W.printModule(fname,tgtname);
1711       break;
1712     case GenContents:
1713       if (fname.empty())
1714         fname = "makeLLVMModuleContents";
1715       W.printContents(fname,tgtname);
1716       break;
1717     case GenFunction:
1718       if (fname.empty())
1719         fname = "makeLLVMFunction";
1720       W.printFunction(fname,tgtname);
1721       break;
1722     case GenInline:
1723       if (fname.empty())
1724         fname = "makeLLVMInline";
1725       W.printInline(fname,tgtname);
1726       break;
1727     case GenVariable:
1728       if (fname.empty())
1729         fname = "makeLLVMVariable";
1730       W.printVariable(fname,tgtname);
1731       break;
1732     case GenType:
1733       if (fname.empty())
1734         fname = "makeLLVMType";
1735       W.printType(fname,tgtname);
1736       break;
1737     default:
1738       W.error("Invalid generation option");
1739   }
1740 }
1741
1742 }