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