ce86452737d91b428b10b1daca9e20ecf4eed382
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Streams.h"
32 #include "llvm/Config/config.h"
33 #include <algorithm>
34 #include <set>
35
36 using namespace llvm;
37
38 static cl::opt<std::string>
39 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
40          cl::value_desc("function name"));
41
42 enum WhatToGenerate {
43   GenProgram,
44   GenModule,
45   GenContents,
46   GenFunction,
47   GenFunctions,
48   GenInline,
49   GenVariable,
50   GenType
51 };
52
53 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
54   cl::desc("Choose what kind of output to generate"),
55   cl::init(GenProgram),
56   cl::values(
57     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
58     clEnumValN(GenModule,   "module",    "Generate a module definition"),
59     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
60     clEnumValN(GenFunction, "function",  "Generate a function definition"),
61     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
63     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
64     clEnumValN(GenType,     "type",      "Generate a type definition"),
65     clEnumValEnd
66   )
67 );
68
69 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
70   cl::desc("Specify the name of the thing to generate"),
71   cl::init("!bad!"));
72
73 // Register the target.
74 static RegisterTarget<CPPTargetMachine> X("cpp", "  C++ backend");
75
76 namespace {
77   typedef std::vector<const Type*> TypeList;
78   typedef std::map<const Type*,std::string> TypeMap;
79   typedef std::map<const Value*,std::string> ValueMap;
80   typedef std::set<std::string> NameSet;
81   typedef std::set<const Type*> TypeSet;
82   typedef std::set<const Value*> ValueSet;
83   typedef std::map<const Value*,std::string> ForwardRefMap;
84
85   /// CppWriter - This class is the main chunk of code that converts an LLVM
86   /// module to a C++ translation unit.
87   class CppWriter : public ModulePass {
88     const char* progname;
89     std::ostream &Out;
90     const Module *TheModule;
91     uint64_t uniqueNum;
92     TypeMap TypeNames;
93     ValueMap ValueNames;
94     TypeMap UnresolvedTypes;
95     TypeList TypeStack;
96     NameSet UsedNames;
97     TypeSet DefinedTypes;
98     ValueSet DefinedValues;
99     ForwardRefMap ForwardRefs;
100     bool is_inline;
101
102   public:
103     static char ID;
104     explicit CppWriter(std::ostream &o) :
105       ModulePass((intptr_t)&ID), Out(o), uniqueNum(0), is_inline(false) {}
106
107     virtual const char *getPassName() const { return "C++ backend"; }
108
109     bool runOnModule(Module &M);
110
111     void printProgram(const std::string& fname, const std::string& modName );
112     void printModule(const std::string& fname, const std::string& modName );
113     void printContents(const std::string& fname, const std::string& modName );
114     void printFunction(const std::string& fname, const std::string& funcName );
115     void printFunctions();
116     void printInline(const std::string& fname, const std::string& funcName );
117     void printVariable(const std::string& fname, const std::string& varName );
118     void printType(const std::string& fname, const std::string& typeName );
119
120     void error(const std::string& msg);
121
122   private:
123     void printLinkageType(GlobalValue::LinkageTypes LT);
124     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
125     void printCallingConv(unsigned cc);
126     void printEscapedString(const std::string& str);
127     void printCFP(const ConstantFP* CFP);
128
129     std::string getCppName(const Type* val);
130     inline void printCppName(const Type* val);
131
132     std::string getCppName(const Value* val);
133     inline void printCppName(const Value* val);
134
135     void printParamAttrs(const PAListPtr &PAL, const std::string &name);
136     bool printTypeInternal(const Type* Ty);
137     inline void printType(const Type* Ty);
138     void printTypes(const Module* M);
139
140     void printConstant(const Constant *CPV);
141     void printConstants(const Module* M);
142
143     void printVariableUses(const GlobalVariable *GV);
144     void printVariableHead(const GlobalVariable *GV);
145     void printVariableBody(const GlobalVariable *GV);
146
147     void printFunctionUses(const Function *F);
148     void printFunctionHead(const Function *F);
149     void printFunctionBody(const Function *F);
150     void printInstruction(const Instruction *I, const std::string& bbname);
151     std::string getOpName(Value*);
152
153     void printModuleBody();
154   };
155
156   static unsigned indent_level = 0;
157   inline std::ostream& nl(std::ostream& Out, int delta = 0) {
158     Out << "\n";
159     if (delta >= 0 || indent_level >= unsigned(-delta))
160       indent_level += delta;
161     for (unsigned i = 0; i < indent_level; ++i)
162       Out << "  ";
163     return Out;
164   }
165
166   inline void in() { indent_level++; }
167   inline void out() { if (indent_level >0) indent_level--; }
168
169   inline void
170   sanitize(std::string& str) {
171     for (size_t i = 0; i < str.length(); ++i)
172       if (!isalnum(str[i]) && str[i] != '_')
173         str[i] = '_';
174   }
175
176   inline std::string
177   getTypePrefix(const Type* Ty ) {
178     switch (Ty->getTypeID()) {
179     case Type::VoidTyID:     return "void_";
180     case Type::IntegerTyID:
181       return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
182         "_";
183     case Type::FloatTyID:    return "float_";
184     case Type::DoubleTyID:   return "double_";
185     case Type::LabelTyID:    return "label_";
186     case Type::FunctionTyID: return "func_";
187     case Type::StructTyID:   return "struct_";
188     case Type::ArrayTyID:    return "array_";
189     case Type::PointerTyID:  return "ptr_";
190     case Type::VectorTyID:   return "packed_";
191     case Type::OpaqueTyID:   return "opaque_";
192     default:                 return "other_";
193     }
194     return "unknown_";
195   }
196
197   // Looks up the type in the symbol table and returns a pointer to its name or
198   // a null pointer if it wasn't found. Note that this isn't the same as the
199   // Mode::getTypeName function which will return an empty string, not a null
200   // pointer if the name is not found.
201   inline const std::string*
202   findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
203     TypeSymbolTable::const_iterator TI = ST.begin();
204     TypeSymbolTable::const_iterator TE = ST.end();
205     for (;TI != TE; ++TI)
206       if (TI->second == Ty)
207         return &(TI->first);
208     return 0;
209   }
210
211   void CppWriter::error(const std::string& msg) {
212     cerr << progname << ": " << msg << "\n";
213     exit(2);
214   }
215
216   // printCFP - Print a floating point constant .. very carefully :)
217   // This makes sure that conversion to/from floating yields the same binary
218   // result so that we don't lose precision.
219   void CppWriter::printCFP(const ConstantFP *CFP) {
220     APFloat APF = APFloat(CFP->getValueAPF());  // copy
221     if (CFP->getType() == Type::FloatTy)
222       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
223     Out << "ConstantFP::get(";
224     Out << "APFloat(";
225 #if HAVE_PRINTF_A
226     char Buffer[100];
227     sprintf(Buffer, "%A", APF.convertToDouble());
228     if ((!strncmp(Buffer, "0x", 2) ||
229          !strncmp(Buffer, "-0x", 3) ||
230          !strncmp(Buffer, "+0x", 3)) &&
231         APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
232       if (CFP->getType() == Type::DoubleTy)
233         Out << "BitsToDouble(" << Buffer << ")";
234       else
235         Out << "BitsToFloat((float)" << Buffer << ")";
236       Out << ")";
237     } else {
238 #endif
239       std::string StrVal = ftostr(CFP->getValueAPF());
240
241       while (StrVal[0] == ' ')
242         StrVal.erase(StrVal.begin());
243
244       // Check to make sure that the stringized number is not some string like
245       // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
246       if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247            ((StrVal[0] == '-' || StrVal[0] == '+') &&
248             (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
249           (CFP->isExactlyValue(atof(StrVal.c_str())))) {
250         if (CFP->getType() == Type::DoubleTy)
251           Out <<  StrVal;
252         else
253           Out << StrVal << "f";
254       } else if (CFP->getType() == Type::DoubleTy)
255         Out << "BitsToDouble(0x" << std::hex
256             << CFP->getValueAPF().convertToAPInt().getZExtValue()
257             << std::dec << "ULL) /* " << StrVal << " */";
258       else
259         Out << "BitsToFloat(0x" << std::hex
260             << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
261             << std::dec << "U) /* " << StrVal << " */";
262       Out << ")";
263 #if HAVE_PRINTF_A
264     }
265 #endif
266     Out << ")";
267   }
268
269   void CppWriter::printCallingConv(unsigned cc){
270     // Print the calling convention.
271     switch (cc) {
272     case CallingConv::C:     Out << "CallingConv::C"; break;
273     case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
274     case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
275     case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
276     default:                 Out << cc; break;
277     }
278   }
279
280   void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
281     switch (LT) {
282     case GlobalValue::InternalLinkage:
283       Out << "GlobalValue::InternalLinkage"; break;
284     case GlobalValue::LinkOnceLinkage:
285       Out << "GlobalValue::LinkOnceLinkage "; break;
286     case GlobalValue::WeakLinkage:
287       Out << "GlobalValue::WeakLinkage"; break;
288     case GlobalValue::AppendingLinkage:
289       Out << "GlobalValue::AppendingLinkage"; break;
290     case GlobalValue::ExternalLinkage:
291       Out << "GlobalValue::ExternalLinkage"; break;
292     case GlobalValue::DLLImportLinkage:
293       Out << "GlobalValue::DLLImportLinkage"; break;
294     case GlobalValue::DLLExportLinkage:
295       Out << "GlobalValue::DLLExportLinkage"; break;
296     case GlobalValue::ExternalWeakLinkage:
297       Out << "GlobalValue::ExternalWeakLinkage"; break;
298     case GlobalValue::GhostLinkage:
299       Out << "GlobalValue::GhostLinkage"; break;
300     case GlobalValue::CommonLinkage:
301       Out << "GlobalValue::CommonLinkage"; break;
302     }
303   }
304
305   void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
306     switch (VisType) {
307     default: assert(0 && "Unknown GVar visibility");
308     case GlobalValue::DefaultVisibility:
309       Out << "GlobalValue::DefaultVisibility";
310       break;
311     case GlobalValue::HiddenVisibility:
312       Out << "GlobalValue::HiddenVisibility";
313       break;
314     case GlobalValue::ProtectedVisibility:
315       Out << "GlobalValue::ProtectedVisibility";
316       break;
317     }
318   }
319
320   // printEscapedString - Print each character of the specified string, escaping
321   // it if it is not printable or if it is an escape char.
322   void CppWriter::printEscapedString(const std::string &Str) {
323     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
324       unsigned char C = Str[i];
325       if (isprint(C) && C != '"' && C != '\\') {
326         Out << C;
327       } else {
328         Out << "\\x"
329             << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
330             << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
331       }
332     }
333   }
334
335   std::string CppWriter::getCppName(const Type* Ty) {
336     // First, handle the primitive types .. easy
337     if (Ty->isPrimitiveType() || Ty->isInteger()) {
338       switch (Ty->getTypeID()) {
339       case Type::VoidTyID:   return "Type::VoidTy";
340       case Type::IntegerTyID: {
341         unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
342         return "IntegerType::get(" + utostr(BitWidth) + ")";
343       }
344       case Type::FloatTyID:  return "Type::FloatTy";
345       case Type::DoubleTyID: return "Type::DoubleTy";
346       case Type::LabelTyID:  return "Type::LabelTy";
347       default:
348         error("Invalid primitive type");
349         break;
350       }
351       return "Type::VoidTy"; // shouldn't be returned, but make it sensible
352     }
353
354     // Now, see if we've seen the type before and return that
355     TypeMap::iterator I = TypeNames.find(Ty);
356     if (I != TypeNames.end())
357       return I->second;
358
359     // Okay, let's build a new name for this type. Start with a prefix
360     const char* prefix = 0;
361     switch (Ty->getTypeID()) {
362     case Type::FunctionTyID:    prefix = "FuncTy_"; break;
363     case Type::StructTyID:      prefix = "StructTy_"; break;
364     case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
365     case Type::PointerTyID:     prefix = "PointerTy_"; break;
366     case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
367     case Type::VectorTyID:      prefix = "VectorTy_"; break;
368     default:                    prefix = "OtherTy_"; break; // prevent breakage
369     }
370
371     // See if the type has a name in the symboltable and build accordingly
372     const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
373     std::string name;
374     if (tName)
375       name = std::string(prefix) + *tName;
376     else
377       name = std::string(prefix) + utostr(uniqueNum++);
378     sanitize(name);
379
380     // Save the name
381     return TypeNames[Ty] = name;
382   }
383
384   void CppWriter::printCppName(const Type* Ty) {
385     printEscapedString(getCppName(Ty));
386   }
387
388   std::string CppWriter::getCppName(const Value* val) {
389     std::string name;
390     ValueMap::iterator I = ValueNames.find(val);
391     if (I != ValueNames.end() && I->first == val)
392       return  I->second;
393
394     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
395       name = std::string("gvar_") +
396         getTypePrefix(GV->getType()->getElementType());
397     } else if (isa<Function>(val)) {
398       name = std::string("func_");
399     } else if (const Constant* C = dyn_cast<Constant>(val)) {
400       name = std::string("const_") + getTypePrefix(C->getType());
401     } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
402       if (is_inline) {
403         unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
404                                         Function::const_arg_iterator(Arg)) + 1;
405         name = std::string("arg_") + utostr(argNum);
406         NameSet::iterator NI = UsedNames.find(name);
407         if (NI != UsedNames.end())
408           name += std::string("_") + utostr(uniqueNum++);
409         UsedNames.insert(name);
410         return ValueNames[val] = name;
411       } else {
412         name = getTypePrefix(val->getType());
413       }
414     } else {
415       name = getTypePrefix(val->getType());
416     }
417     name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
418     sanitize(name);
419     NameSet::iterator NI = UsedNames.find(name);
420     if (NI != UsedNames.end())
421       name += std::string("_") + utostr(uniqueNum++);
422     UsedNames.insert(name);
423     return ValueNames[val] = name;
424   }
425
426   void CppWriter::printCppName(const Value* val) {
427     printEscapedString(getCppName(val));
428   }
429
430   void CppWriter::printParamAttrs(const PAListPtr &PAL,
431                                   const std::string &name) {
432     Out << "PAListPtr " << name << "_PAL;";
433     nl(Out);
434     if (!PAL.isEmpty()) {
435       Out << '{'; in(); nl(Out);
436       Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
437       Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
438       for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
439         uint16_t index = PAL.getSlot(i).Index;
440         ParameterAttributes attrs = PAL.getSlot(i).Attrs;
441         Out << "PAWI.Index = " << index << "; PAWI.Attrs = 0 ";
442         if (attrs & ParamAttr::SExt)
443           Out << " | ParamAttr::SExt";
444         if (attrs & ParamAttr::ZExt)
445           Out << " | ParamAttr::ZExt";
446         if (attrs & ParamAttr::StructRet)
447           Out << " | ParamAttr::StructRet";
448         if (attrs & ParamAttr::InReg)
449           Out << " | ParamAttr::InReg";
450         if (attrs & ParamAttr::NoReturn)
451           Out << " | ParamAttr::NoReturn";
452         if (attrs & ParamAttr::NoUnwind)
453           Out << " | ParamAttr::NoUnwind";
454         if (attrs & ParamAttr::ByVal)
455           Out << " | ParamAttr::ByVal";
456         if (attrs & ParamAttr::NoAlias)
457           Out << " | ParamAttr::NoAlias";
458         if (attrs & ParamAttr::Nest)
459           Out << " | ParamAttr::Nest";
460         if (attrs & ParamAttr::ReadNone)
461           Out << " | ParamAttr::ReadNone";
462         if (attrs & ParamAttr::ReadOnly)
463           Out << " | ParamAttr::ReadOnly";
464         Out << ";";
465         nl(Out);
466         Out << "Attrs.push_back(PAWI);";
467         nl(Out);
468       }
469       Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
470       nl(Out);
471       out(); nl(Out);
472       Out << '}'; nl(Out);
473     }
474   }
475
476   bool CppWriter::printTypeInternal(const Type* Ty) {
477     // We don't print definitions for primitive types
478     if (Ty->isPrimitiveType() || Ty->isInteger())
479       return false;
480
481     // If we already defined this type, we don't need to define it again.
482     if (DefinedTypes.find(Ty) != DefinedTypes.end())
483       return false;
484
485     // Everything below needs the name for the type so get it now.
486     std::string typeName(getCppName(Ty));
487
488     // Search the type stack for recursion. If we find it, then generate this
489     // as an OpaqueType, but make sure not to do this multiple times because
490     // the type could appear in multiple places on the stack. Once the opaque
491     // definition is issued, it must not be re-issued. Consequently we have to
492     // check the UnresolvedTypes list as well.
493     TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
494                                             Ty);
495     if (TI != TypeStack.end()) {
496       TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
497       if (I == UnresolvedTypes.end()) {
498         Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
499         nl(Out);
500         UnresolvedTypes[Ty] = typeName;
501       }
502       return true;
503     }
504
505     // We're going to print a derived type which, by definition, contains other
506     // types. So, push this one we're printing onto the type stack to assist with
507     // recursive definitions.
508     TypeStack.push_back(Ty);
509
510     // Print the type definition
511     switch (Ty->getTypeID()) {
512     case Type::FunctionTyID:  {
513       const FunctionType* FT = cast<FunctionType>(Ty);
514       Out << "std::vector<const Type*>" << typeName << "_args;";
515       nl(Out);
516       FunctionType::param_iterator PI = FT->param_begin();
517       FunctionType::param_iterator PE = FT->param_end();
518       for (; PI != PE; ++PI) {
519         const Type* argTy = static_cast<const Type*>(*PI);
520         bool isForward = printTypeInternal(argTy);
521         std::string argName(getCppName(argTy));
522         Out << typeName << "_args.push_back(" << argName;
523         if (isForward)
524           Out << "_fwd";
525         Out << ");";
526         nl(Out);
527       }
528       bool isForward = printTypeInternal(FT->getReturnType());
529       std::string retTypeName(getCppName(FT->getReturnType()));
530       Out << "FunctionType* " << typeName << " = FunctionType::get(";
531       in(); nl(Out) << "/*Result=*/" << retTypeName;
532       if (isForward)
533         Out << "_fwd";
534       Out << ",";
535       nl(Out) << "/*Params=*/" << typeName << "_args,";
536       nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
537       out();
538       nl(Out);
539       break;
540     }
541     case Type::StructTyID: {
542       const StructType* ST = cast<StructType>(Ty);
543       Out << "std::vector<const Type*>" << typeName << "_fields;";
544       nl(Out);
545       StructType::element_iterator EI = ST->element_begin();
546       StructType::element_iterator EE = ST->element_end();
547       for (; EI != EE; ++EI) {
548         const Type* fieldTy = static_cast<const Type*>(*EI);
549         bool isForward = printTypeInternal(fieldTy);
550         std::string fieldName(getCppName(fieldTy));
551         Out << typeName << "_fields.push_back(" << fieldName;
552         if (isForward)
553           Out << "_fwd";
554         Out << ");";
555         nl(Out);
556       }
557       Out << "StructType* " << typeName << " = StructType::get("
558           << typeName << "_fields, /*isPacked=*/"
559           << (ST->isPacked() ? "true" : "false") << ");";
560       nl(Out);
561       break;
562     }
563     case Type::ArrayTyID: {
564       const ArrayType* AT = cast<ArrayType>(Ty);
565       const Type* ET = AT->getElementType();
566       bool isForward = printTypeInternal(ET);
567       std::string elemName(getCppName(ET));
568       Out << "ArrayType* " << typeName << " = ArrayType::get("
569           << elemName << (isForward ? "_fwd" : "")
570           << ", " << utostr(AT->getNumElements()) << ");";
571       nl(Out);
572       break;
573     }
574     case Type::PointerTyID: {
575       const PointerType* PT = cast<PointerType>(Ty);
576       const Type* ET = PT->getElementType();
577       bool isForward = printTypeInternal(ET);
578       std::string elemName(getCppName(ET));
579       Out << "PointerType* " << typeName << " = PointerType::get("
580           << elemName << (isForward ? "_fwd" : "")
581           << ", " << utostr(PT->getAddressSpace()) << ");";
582       nl(Out);
583       break;
584     }
585     case Type::VectorTyID: {
586       const VectorType* PT = cast<VectorType>(Ty);
587       const Type* ET = PT->getElementType();
588       bool isForward = printTypeInternal(ET);
589       std::string elemName(getCppName(ET));
590       Out << "VectorType* " << typeName << " = VectorType::get("
591           << elemName << (isForward ? "_fwd" : "")
592           << ", " << utostr(PT->getNumElements()) << ");";
593       nl(Out);
594       break;
595     }
596     case Type::OpaqueTyID: {
597       Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
598       nl(Out);
599       break;
600     }
601     default:
602       error("Invalid TypeID");
603     }
604
605     // If the type had a name, make sure we recreate it.
606     const std::string* progTypeName =
607       findTypeName(TheModule->getTypeSymbolTable(),Ty);
608     if (progTypeName) {
609       Out << "mod->addTypeName(\"" << *progTypeName << "\", "
610           << typeName << ");";
611       nl(Out);
612     }
613
614     // Pop us off the type stack
615     TypeStack.pop_back();
616
617     // Indicate that this type is now defined.
618     DefinedTypes.insert(Ty);
619
620     // Early resolve as many unresolved types as possible. Search the unresolved
621     // types map for the type we just printed. Now that its definition is complete
622     // we can resolve any previous references to it. This prevents a cascade of
623     // unresolved types.
624     TypeMap::iterator I = UnresolvedTypes.find(Ty);
625     if (I != UnresolvedTypes.end()) {
626       Out << "cast<OpaqueType>(" << I->second
627           << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
628       nl(Out);
629       Out << I->second << " = cast<";
630       switch (Ty->getTypeID()) {
631       case Type::FunctionTyID: Out << "FunctionType"; break;
632       case Type::ArrayTyID:    Out << "ArrayType"; break;
633       case Type::StructTyID:   Out << "StructType"; break;
634       case Type::VectorTyID:   Out << "VectorType"; break;
635       case Type::PointerTyID:  Out << "PointerType"; break;
636       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
637       default:                 Out << "NoSuchDerivedType"; break;
638       }
639       Out << ">(" << I->second << "_fwd.get());";
640       nl(Out); nl(Out);
641       UnresolvedTypes.erase(I);
642     }
643
644     // Finally, separate the type definition from other with a newline.
645     nl(Out);
646
647     // We weren't a recursive type
648     return false;
649   }
650
651   // Prints a type definition. Returns true if it could not resolve all the
652   // types in the definition but had to use a forward reference.
653   void CppWriter::printType(const Type* Ty) {
654     assert(TypeStack.empty());
655     TypeStack.clear();
656     printTypeInternal(Ty);
657     assert(TypeStack.empty());
658   }
659
660   void CppWriter::printTypes(const Module* M) {
661     // Walk the symbol table and print out all its types
662     const TypeSymbolTable& symtab = M->getTypeSymbolTable();
663     for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
664          TI != TE; ++TI) {
665
666       // For primitive types and types already defined, just add a name
667       TypeMap::const_iterator TNI = TypeNames.find(TI->second);
668       if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
669           TNI != TypeNames.end()) {
670         Out << "mod->addTypeName(\"";
671         printEscapedString(TI->first);
672         Out << "\", " << getCppName(TI->second) << ");";
673         nl(Out);
674         // For everything else, define the type
675       } else {
676         printType(TI->second);
677       }
678     }
679
680     // Add all of the global variables to the value table...
681     for (Module::const_global_iterator I = TheModule->global_begin(),
682            E = TheModule->global_end(); I != E; ++I) {
683       if (I->hasInitializer())
684         printType(I->getInitializer()->getType());
685       printType(I->getType());
686     }
687
688     // Add all the functions to the table
689     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
690          FI != FE; ++FI) {
691       printType(FI->getReturnType());
692       printType(FI->getFunctionType());
693       // Add all the function arguments
694       for (Function::const_arg_iterator AI = FI->arg_begin(),
695              AE = FI->arg_end(); AI != AE; ++AI) {
696         printType(AI->getType());
697       }
698
699       // Add all of the basic blocks and instructions
700       for (Function::const_iterator BB = FI->begin(),
701              E = FI->end(); BB != E; ++BB) {
702         printType(BB->getType());
703         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
704              ++I) {
705           printType(I->getType());
706           for (unsigned i = 0; i < I->getNumOperands(); ++i)
707             printType(I->getOperand(i)->getType());
708         }
709       }
710     }
711   }
712
713
714   // printConstant - Print out a constant pool entry...
715   void CppWriter::printConstant(const Constant *CV) {
716     // First, if the constant is actually a GlobalValue (variable or function)
717     // or its already in the constant list then we've printed it already and we
718     // can just return.
719     if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
720       return;
721
722     std::string constName(getCppName(CV));
723     std::string typeName(getCppName(CV->getType()));
724     if (CV->isNullValue()) {
725       Out << "Constant* " << constName << " = Constant::getNullValue("
726           << typeName << ");";
727       nl(Out);
728       return;
729     }
730     if (isa<GlobalValue>(CV)) {
731       // Skip variables and functions, we emit them elsewhere
732       return;
733     }
734     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
735       Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
736           << cast<IntegerType>(CI->getType())->getBitWidth() << ",  \""
737           << CI->getValue() << "\", 10));";
738     } else if (isa<ConstantAggregateZero>(CV)) {
739       Out << "ConstantAggregateZero* " << constName
740           << " = ConstantAggregateZero::get(" << typeName << ");";
741     } else if (isa<ConstantPointerNull>(CV)) {
742       Out << "ConstantPointerNull* " << constName
743           << " = ConstanPointerNull::get(" << typeName << ");";
744     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
745       Out << "ConstantFP* " << constName << " = ";
746       printCFP(CFP);
747       Out << ";";
748     } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
749       if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
750         Out << "Constant* " << constName << " = ConstantArray::get(\"";
751         std::string tmp = CA->getAsString();
752         bool nullTerminate = false;
753         if (tmp[tmp.length()-1] == 0) {
754           tmp.erase(tmp.length()-1);
755           nullTerminate = true;
756         }
757         printEscapedString(tmp);
758         // Determine if we want null termination or not.
759         if (nullTerminate)
760           Out << "\", true"; // Indicate that the null terminator should be
761                              // added.
762         else
763           Out << "\", false";// No null terminator
764         Out << ");";
765       } else {
766         Out << "std::vector<Constant*> " << constName << "_elems;";
767         nl(Out);
768         unsigned N = CA->getNumOperands();
769         for (unsigned i = 0; i < N; ++i) {
770           printConstant(CA->getOperand(i)); // recurse to print operands
771           Out << constName << "_elems.push_back("
772               << getCppName(CA->getOperand(i)) << ");";
773           nl(Out);
774         }
775         Out << "Constant* " << constName << " = ConstantArray::get("
776             << typeName << ", " << constName << "_elems);";
777       }
778     } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
779       Out << "std::vector<Constant*> " << constName << "_fields;";
780       nl(Out);
781       unsigned N = CS->getNumOperands();
782       for (unsigned i = 0; i < N; i++) {
783         printConstant(CS->getOperand(i));
784         Out << constName << "_fields.push_back("
785             << getCppName(CS->getOperand(i)) << ");";
786         nl(Out);
787       }
788       Out << "Constant* " << constName << " = ConstantStruct::get("
789           << typeName << ", " << constName << "_fields);";
790     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
791       Out << "std::vector<Constant*> " << constName << "_elems;";
792       nl(Out);
793       unsigned N = CP->getNumOperands();
794       for (unsigned i = 0; i < N; ++i) {
795         printConstant(CP->getOperand(i));
796         Out << constName << "_elems.push_back("
797             << getCppName(CP->getOperand(i)) << ");";
798         nl(Out);
799       }
800       Out << "Constant* " << constName << " = ConstantVector::get("
801           << typeName << ", " << constName << "_elems);";
802     } else if (isa<UndefValue>(CV)) {
803       Out << "UndefValue* " << constName << " = UndefValue::get("
804           << typeName << ");";
805     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
806       if (CE->getOpcode() == Instruction::GetElementPtr) {
807         Out << "std::vector<Constant*> " << constName << "_indices;";
808         nl(Out);
809         printConstant(CE->getOperand(0));
810         for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
811           printConstant(CE->getOperand(i));
812           Out << constName << "_indices.push_back("
813               << getCppName(CE->getOperand(i)) << ");";
814           nl(Out);
815         }
816         Out << "Constant* " << constName
817             << " = ConstantExpr::getGetElementPtr("
818             << getCppName(CE->getOperand(0)) << ", "
819             << "&" << constName << "_indices[0], "
820             << constName << "_indices.size()"
821             << " );";
822       } else if (CE->isCast()) {
823         printConstant(CE->getOperand(0));
824         Out << "Constant* " << constName << " = ConstantExpr::getCast(";
825         switch (CE->getOpcode()) {
826         default: assert(0 && "Invalid cast opcode");
827         case Instruction::Trunc: Out << "Instruction::Trunc"; break;
828         case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
829         case Instruction::SExt:  Out << "Instruction::SExt"; break;
830         case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
831         case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
832         case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
833         case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
834         case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
835         case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
836         case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
837         case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
838         case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
839         }
840         Out << ", " << getCppName(CE->getOperand(0)) << ", "
841             << getCppName(CE->getType()) << ");";
842       } else {
843         unsigned N = CE->getNumOperands();
844         for (unsigned i = 0; i < N; ++i ) {
845           printConstant(CE->getOperand(i));
846         }
847         Out << "Constant* " << constName << " = ConstantExpr::";
848         switch (CE->getOpcode()) {
849         case Instruction::Add:    Out << "getAdd(";  break;
850         case Instruction::Sub:    Out << "getSub("; break;
851         case Instruction::Mul:    Out << "getMul("; break;
852         case Instruction::UDiv:   Out << "getUDiv("; break;
853         case Instruction::SDiv:   Out << "getSDiv("; break;
854         case Instruction::FDiv:   Out << "getFDiv("; break;
855         case Instruction::URem:   Out << "getURem("; break;
856         case Instruction::SRem:   Out << "getSRem("; break;
857         case Instruction::FRem:   Out << "getFRem("; break;
858         case Instruction::And:    Out << "getAnd("; break;
859         case Instruction::Or:     Out << "getOr("; break;
860         case Instruction::Xor:    Out << "getXor("; break;
861         case Instruction::ICmp:
862           Out << "getICmp(ICmpInst::ICMP_";
863           switch (CE->getPredicate()) {
864           case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
865           case ICmpInst::ICMP_NE:  Out << "NE"; break;
866           case ICmpInst::ICMP_SLT: Out << "SLT"; break;
867           case ICmpInst::ICMP_ULT: Out << "ULT"; break;
868           case ICmpInst::ICMP_SGT: Out << "SGT"; break;
869           case ICmpInst::ICMP_UGT: Out << "UGT"; break;
870           case ICmpInst::ICMP_SLE: Out << "SLE"; break;
871           case ICmpInst::ICMP_ULE: Out << "ULE"; break;
872           case ICmpInst::ICMP_SGE: Out << "SGE"; break;
873           case ICmpInst::ICMP_UGE: Out << "UGE"; break;
874           default: error("Invalid ICmp Predicate");
875           }
876           break;
877         case Instruction::FCmp:
878           Out << "getFCmp(FCmpInst::FCMP_";
879           switch (CE->getPredicate()) {
880           case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
881           case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
882           case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
883           case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
884           case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
885           case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
886           case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
887           case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
888           case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
889           case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
890           case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
891           case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
892           case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
893           case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
894           case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
895           case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
896           default: error("Invalid FCmp Predicate");
897           }
898           break;
899         case Instruction::Shl:     Out << "getShl("; break;
900         case Instruction::LShr:    Out << "getLShr("; break;
901         case Instruction::AShr:    Out << "getAShr("; break;
902         case Instruction::Select:  Out << "getSelect("; break;
903         case Instruction::ExtractElement: Out << "getExtractElement("; break;
904         case Instruction::InsertElement:  Out << "getInsertElement("; break;
905         case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
906         default:
907           error("Invalid constant expression");
908           break;
909         }
910         Out << getCppName(CE->getOperand(0));
911         for (unsigned i = 1; i < CE->getNumOperands(); ++i)
912           Out << ", " << getCppName(CE->getOperand(i));
913         Out << ");";
914       }
915     } else {
916       error("Bad Constant");
917       Out << "Constant* " << constName << " = 0; ";
918     }
919     nl(Out);
920   }
921
922   void CppWriter::printConstants(const Module* M) {
923     // Traverse all the global variables looking for constant initializers
924     for (Module::const_global_iterator I = TheModule->global_begin(),
925            E = TheModule->global_end(); I != E; ++I)
926       if (I->hasInitializer())
927         printConstant(I->getInitializer());
928
929     // Traverse the LLVM functions looking for constants
930     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
931          FI != FE; ++FI) {
932       // Add all of the basic blocks and instructions
933       for (Function::const_iterator BB = FI->begin(),
934              E = FI->end(); BB != E; ++BB) {
935         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
936              ++I) {
937           for (unsigned i = 0; i < I->getNumOperands(); ++i) {
938             if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
939               printConstant(C);
940             }
941           }
942         }
943       }
944     }
945   }
946
947   void CppWriter::printVariableUses(const GlobalVariable *GV) {
948     nl(Out) << "// Type Definitions";
949     nl(Out);
950     printType(GV->getType());
951     if (GV->hasInitializer()) {
952       Constant* Init = GV->getInitializer();
953       printType(Init->getType());
954       if (Function* F = dyn_cast<Function>(Init)) {
955         nl(Out)<< "/ Function Declarations"; nl(Out);
956         printFunctionHead(F);
957       } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
958         nl(Out) << "// Global Variable Declarations"; nl(Out);
959         printVariableHead(gv);
960       } else  {
961         nl(Out) << "// Constant Definitions"; nl(Out);
962         printConstant(gv);
963       }
964       if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
965         nl(Out) << "// Global Variable Definitions"; nl(Out);
966         printVariableBody(gv);
967       }
968     }
969   }
970
971   void CppWriter::printVariableHead(const GlobalVariable *GV) {
972     nl(Out) << "GlobalVariable* " << getCppName(GV);
973     if (is_inline) {
974       Out << " = mod->getGlobalVariable(";
975       printEscapedString(GV->getName());
976       Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
977       nl(Out) << "if (!" << getCppName(GV) << ") {";
978       in(); nl(Out) << getCppName(GV);
979     }
980     Out << " = new GlobalVariable(";
981     nl(Out) << "/*Type=*/";
982     printCppName(GV->getType()->getElementType());
983     Out << ",";
984     nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
985     Out << ",";
986     nl(Out) << "/*Linkage=*/";
987     printLinkageType(GV->getLinkage());
988     Out << ",";
989     nl(Out) << "/*Initializer=*/0, ";
990     if (GV->hasInitializer()) {
991       Out << "// has initializer, specified below";
992     }
993     nl(Out) << "/*Name=*/\"";
994     printEscapedString(GV->getName());
995     Out << "\",";
996     nl(Out) << "mod);";
997     nl(Out);
998
999     if (GV->hasSection()) {
1000       printCppName(GV);
1001       Out << "->setSection(\"";
1002       printEscapedString(GV->getSection());
1003       Out << "\");";
1004       nl(Out);
1005     }
1006     if (GV->getAlignment()) {
1007       printCppName(GV);
1008       Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1009       nl(Out);
1010     }
1011     if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1012       printCppName(GV);
1013       Out << "->setVisibility(";
1014       printVisibilityType(GV->getVisibility());
1015       Out << ");";
1016       nl(Out);
1017     }
1018     if (is_inline) {
1019       out(); Out << "}"; nl(Out);
1020     }
1021   }
1022
1023   void CppWriter::printVariableBody(const GlobalVariable *GV) {
1024     if (GV->hasInitializer()) {
1025       printCppName(GV);
1026       Out << "->setInitializer(";
1027       Out << getCppName(GV->getInitializer()) << ");";
1028       nl(Out);
1029     }
1030   }
1031
1032   std::string CppWriter::getOpName(Value* V) {
1033     if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1034       return getCppName(V);
1035
1036     // See if its alread in the map of forward references, if so just return the
1037     // name we already set up for it
1038     ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1039     if (I != ForwardRefs.end())
1040       return I->second;
1041
1042     // This is a new forward reference. Generate a unique name for it
1043     std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1044
1045     // Yes, this is a hack. An Argument is the smallest instantiable value that
1046     // we can make as a placeholder for the real value. We'll replace these
1047     // Argument instances later.
1048     Out << "Argument* " << result << " = new Argument("
1049         << getCppName(V->getType()) << ");";
1050     nl(Out);
1051     ForwardRefs[V] = result;
1052     return result;
1053   }
1054
1055   // printInstruction - This member is called for each Instruction in a function.
1056   void CppWriter::printInstruction(const Instruction *I,
1057                                    const std::string& bbname) {
1058     std::string iName(getCppName(I));
1059
1060     // Before we emit this instruction, we need to take care of generating any
1061     // forward references. So, we get the names of all the operands in advance
1062     std::string* opNames = new std::string[I->getNumOperands()];
1063     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1064       opNames[i] = getOpName(I->getOperand(i));
1065     }
1066
1067     switch (I->getOpcode()) {
1068     default:
1069       error("Invalid instruction");
1070       break;
1071
1072     case Instruction::Ret: {
1073       const ReturnInst* ret =  cast<ReturnInst>(I);
1074       Out << "ReturnInst::Create("
1075           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1076       break;
1077     }
1078     case Instruction::Br: {
1079       const BranchInst* br = cast<BranchInst>(I);
1080       Out << "BranchInst::Create(" ;
1081       if (br->getNumOperands() == 3 ) {
1082         Out << opNames[0] << ", "
1083             << opNames[1] << ", "
1084             << opNames[2] << ", ";
1085
1086       } else if (br->getNumOperands() == 1) {
1087         Out << opNames[0] << ", ";
1088       } else {
1089         error("Branch with 2 operands?");
1090       }
1091       Out << bbname << ");";
1092       break;
1093     }
1094     case Instruction::Switch: {
1095       const SwitchInst* sw = cast<SwitchInst>(I);
1096       Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1097           << opNames[0] << ", "
1098           << opNames[1] << ", "
1099           << sw->getNumCases() << ", " << bbname << ");";
1100       nl(Out);
1101       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1102         Out << iName << "->addCase("
1103             << opNames[i] << ", "
1104             << opNames[i+1] << ");";
1105         nl(Out);
1106       }
1107       break;
1108     }
1109     case Instruction::Invoke: {
1110       const InvokeInst* inv = cast<InvokeInst>(I);
1111       Out << "std::vector<Value*> " << iName << "_params;";
1112       nl(Out);
1113       for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1114         Out << iName << "_params.push_back("
1115             << opNames[i] << ");";
1116         nl(Out);
1117       }
1118       Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1119           << opNames[0] << ", "
1120           << opNames[1] << ", "
1121           << opNames[2] << ", "
1122           << iName << "_params.begin(), " << iName << "_params.end(), \"";
1123       printEscapedString(inv->getName());
1124       Out << "\", " << bbname << ");";
1125       nl(Out) << iName << "->setCallingConv(";
1126       printCallingConv(inv->getCallingConv());
1127       Out << ");";
1128       printParamAttrs(inv->getParamAttrs(), iName);
1129       Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1130       nl(Out);
1131       break;
1132     }
1133     case Instruction::Unwind: {
1134       Out << "new UnwindInst("
1135           << bbname << ");";
1136       break;
1137     }
1138     case Instruction::Unreachable:{
1139       Out << "new UnreachableInst("
1140           << bbname << ");";
1141       break;
1142     }
1143     case Instruction::Add:
1144     case Instruction::Sub:
1145     case Instruction::Mul:
1146     case Instruction::UDiv:
1147     case Instruction::SDiv:
1148     case Instruction::FDiv:
1149     case Instruction::URem:
1150     case Instruction::SRem:
1151     case Instruction::FRem:
1152     case Instruction::And:
1153     case Instruction::Or:
1154     case Instruction::Xor:
1155     case Instruction::Shl:
1156     case Instruction::LShr:
1157     case Instruction::AShr:{
1158       Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1159       switch (I->getOpcode()) {
1160       case Instruction::Add: Out << "Instruction::Add"; break;
1161       case Instruction::Sub: Out << "Instruction::Sub"; break;
1162       case Instruction::Mul: Out << "Instruction::Mul"; break;
1163       case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1164       case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1165       case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1166       case Instruction::URem:Out << "Instruction::URem"; break;
1167       case Instruction::SRem:Out << "Instruction::SRem"; break;
1168       case Instruction::FRem:Out << "Instruction::FRem"; break;
1169       case Instruction::And: Out << "Instruction::And"; break;
1170       case Instruction::Or:  Out << "Instruction::Or";  break;
1171       case Instruction::Xor: Out << "Instruction::Xor"; break;
1172       case Instruction::Shl: Out << "Instruction::Shl"; break;
1173       case Instruction::LShr:Out << "Instruction::LShr"; break;
1174       case Instruction::AShr:Out << "Instruction::AShr"; break;
1175       default: Out << "Instruction::BadOpCode"; break;
1176       }
1177       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1178       printEscapedString(I->getName());
1179       Out << "\", " << bbname << ");";
1180       break;
1181     }
1182     case Instruction::FCmp: {
1183       Out << "FCmpInst* " << iName << " = new FCmpInst(";
1184       switch (cast<FCmpInst>(I)->getPredicate()) {
1185       case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1186       case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1187       case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1188       case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1189       case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1190       case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1191       case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1192       case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1193       case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1194       case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1195       case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1196       case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1197       case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1198       case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1199       case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1200       case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1201       default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1202       }
1203       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1204       printEscapedString(I->getName());
1205       Out << "\", " << bbname << ");";
1206       break;
1207     }
1208     case Instruction::ICmp: {
1209       Out << "ICmpInst* " << iName << " = new ICmpInst(";
1210       switch (cast<ICmpInst>(I)->getPredicate()) {
1211       case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1212       case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1213       case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1214       case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1215       case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1216       case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1217       case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1218       case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1219       case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1220       case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1221       default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1222       }
1223       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1224       printEscapedString(I->getName());
1225       Out << "\", " << bbname << ");";
1226       break;
1227     }
1228     case Instruction::Malloc: {
1229       const MallocInst* mallocI = cast<MallocInst>(I);
1230       Out << "MallocInst* " << iName << " = new MallocInst("
1231           << getCppName(mallocI->getAllocatedType()) << ", ";
1232       if (mallocI->isArrayAllocation())
1233         Out << opNames[0] << ", " ;
1234       Out << "\"";
1235       printEscapedString(mallocI->getName());
1236       Out << "\", " << bbname << ");";
1237       if (mallocI->getAlignment())
1238         nl(Out) << iName << "->setAlignment("
1239             << mallocI->getAlignment() << ");";
1240       break;
1241     }
1242     case Instruction::Free: {
1243       Out << "FreeInst* " << iName << " = new FreeInst("
1244           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1245       break;
1246     }
1247     case Instruction::Alloca: {
1248       const AllocaInst* allocaI = cast<AllocaInst>(I);
1249       Out << "AllocaInst* " << iName << " = new AllocaInst("
1250           << getCppName(allocaI->getAllocatedType()) << ", ";
1251       if (allocaI->isArrayAllocation())
1252         Out << opNames[0] << ", ";
1253       Out << "\"";
1254       printEscapedString(allocaI->getName());
1255       Out << "\", " << bbname << ");";
1256       if (allocaI->getAlignment())
1257         nl(Out) << iName << "->setAlignment("
1258             << allocaI->getAlignment() << ");";
1259       break;
1260     }
1261     case Instruction::Load:{
1262       const LoadInst* load = cast<LoadInst>(I);
1263       Out << "LoadInst* " << iName << " = new LoadInst("
1264           << opNames[0] << ", \"";
1265       printEscapedString(load->getName());
1266       Out << "\", " << (load->isVolatile() ? "true" : "false" )
1267           << ", " << bbname << ");";
1268       break;
1269     }
1270     case Instruction::Store: {
1271       const StoreInst* store = cast<StoreInst>(I);
1272       Out << "StoreInst* " << iName << " = new StoreInst("
1273           << opNames[0] << ", "
1274           << opNames[1] << ", "
1275           << (store->isVolatile() ? "true" : "false")
1276           << ", " << bbname << ");";
1277       break;
1278     }
1279     case Instruction::GetElementPtr: {
1280       const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1281       if (gep->getNumOperands() <= 2) {
1282         Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1283             << opNames[0];
1284         if (gep->getNumOperands() == 2)
1285           Out << ", " << opNames[1];
1286       } else {
1287         Out << "std::vector<Value*> " << iName << "_indices;";
1288         nl(Out);
1289         for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1290           Out << iName << "_indices.push_back("
1291               << opNames[i] << ");";
1292           nl(Out);
1293         }
1294         Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1295             << opNames[0] << ", " << iName << "_indices.begin(), "
1296             << iName << "_indices.end()";
1297       }
1298       Out << ", \"";
1299       printEscapedString(gep->getName());
1300       Out << "\", " << bbname << ");";
1301       break;
1302     }
1303     case Instruction::PHI: {
1304       const PHINode* phi = cast<PHINode>(I);
1305
1306       Out << "PHINode* " << iName << " = PHINode::Create("
1307           << getCppName(phi->getType()) << ", \"";
1308       printEscapedString(phi->getName());
1309       Out << "\", " << bbname << ");";
1310       nl(Out) << iName << "->reserveOperandSpace("
1311         << phi->getNumIncomingValues()
1312           << ");";
1313       nl(Out);
1314       for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1315         Out << iName << "->addIncoming("
1316             << opNames[i] << ", " << opNames[i+1] << ");";
1317         nl(Out);
1318       }
1319       break;
1320     }
1321     case Instruction::Trunc:
1322     case Instruction::ZExt:
1323     case Instruction::SExt:
1324     case Instruction::FPTrunc:
1325     case Instruction::FPExt:
1326     case Instruction::FPToUI:
1327     case Instruction::FPToSI:
1328     case Instruction::UIToFP:
1329     case Instruction::SIToFP:
1330     case Instruction::PtrToInt:
1331     case Instruction::IntToPtr:
1332     case Instruction::BitCast: {
1333       const CastInst* cst = cast<CastInst>(I);
1334       Out << "CastInst* " << iName << " = new ";
1335       switch (I->getOpcode()) {
1336       case Instruction::Trunc:    Out << "TruncInst"; break;
1337       case Instruction::ZExt:     Out << "ZExtInst"; break;
1338       case Instruction::SExt:     Out << "SExtInst"; break;
1339       case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1340       case Instruction::FPExt:    Out << "FPExtInst"; break;
1341       case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1342       case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1343       case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1344       case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1345       case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1346       case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1347       case Instruction::BitCast:  Out << "BitCastInst"; break;
1348       default: assert(!"Unreachable"); break;
1349       }
1350       Out << "(" << opNames[0] << ", "
1351           << getCppName(cst->getType()) << ", \"";
1352       printEscapedString(cst->getName());
1353       Out << "\", " << bbname << ");";
1354       break;
1355     }
1356     case Instruction::Call:{
1357       const CallInst* call = cast<CallInst>(I);
1358       if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1359         Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1360             << getCppName(ila->getFunctionType()) << ", \""
1361             << ila->getAsmString() << "\", \""
1362             << ila->getConstraintString() << "\","
1363             << (ila->hasSideEffects() ? "true" : "false") << ");";
1364         nl(Out);
1365       }
1366       if (call->getNumOperands() > 2) {
1367         Out << "std::vector<Value*> " << iName << "_params;";
1368         nl(Out);
1369         for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1370           Out << iName << "_params.push_back(" << opNames[i] << ");";
1371           nl(Out);
1372         }
1373         Out << "CallInst* " << iName << " = CallInst::Create("
1374             << opNames[0] << ", " << iName << "_params.begin(), "
1375             << iName << "_params.end(), \"";
1376       } else if (call->getNumOperands() == 2) {
1377         Out << "CallInst* " << iName << " = CallInst::Create("
1378             << opNames[0] << ", " << opNames[1] << ", \"";
1379       } else {
1380         Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1381             << ", \"";
1382       }
1383       printEscapedString(call->getName());
1384       Out << "\", " << bbname << ");";
1385       nl(Out) << iName << "->setCallingConv(";
1386       printCallingConv(call->getCallingConv());
1387       Out << ");";
1388       nl(Out) << iName << "->setTailCall("
1389           << (call->isTailCall() ? "true":"false");
1390       Out << ");";
1391       printParamAttrs(call->getParamAttrs(), iName);
1392       Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1393       nl(Out);
1394       break;
1395     }
1396     case Instruction::Select: {
1397       const SelectInst* sel = cast<SelectInst>(I);
1398       Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1399       Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1400       printEscapedString(sel->getName());
1401       Out << "\", " << bbname << ");";
1402       break;
1403     }
1404     case Instruction::UserOp1:
1405       /// FALL THROUGH
1406     case Instruction::UserOp2: {
1407       /// FIXME: What should be done here?
1408       break;
1409     }
1410     case Instruction::VAArg: {
1411       const VAArgInst* va = cast<VAArgInst>(I);
1412       Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1413           << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1414       printEscapedString(va->getName());
1415       Out << "\", " << bbname << ");";
1416       break;
1417     }
1418     case Instruction::ExtractElement: {
1419       const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1420       Out << "ExtractElementInst* " << getCppName(eei)
1421           << " = new ExtractElementInst(" << opNames[0]
1422           << ", " << opNames[1] << ", \"";
1423       printEscapedString(eei->getName());
1424       Out << "\", " << bbname << ");";
1425       break;
1426     }
1427     case Instruction::InsertElement: {
1428       const InsertElementInst* iei = cast<InsertElementInst>(I);
1429       Out << "InsertElementInst* " << getCppName(iei)
1430           << " = InsertElementInst::Create(" << opNames[0]
1431           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1432       printEscapedString(iei->getName());
1433       Out << "\", " << bbname << ");";
1434       break;
1435     }
1436     case Instruction::ShuffleVector: {
1437       const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1438       Out << "ShuffleVectorInst* " << getCppName(svi)
1439           << " = new ShuffleVectorInst(" << opNames[0]
1440           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1441       printEscapedString(svi->getName());
1442       Out << "\", " << bbname << ");";
1443       break;
1444     }
1445     case Instruction::ExtractValue: {
1446       const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1447       Out << "std::vector<unsigned> " << iName << "_indices;";
1448       nl(Out);
1449       for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1450         Out << iName << "_indices.push_back("
1451             << evi->idx_begin()[i] << ");";
1452         nl(Out);
1453       }
1454       Out << "ExtractValueInst* " << getCppName(evi)
1455           << " = ExtractValueInst::Create(" << opNames[0]
1456           << ", "
1457           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1458       printEscapedString(evi->getName());
1459       Out << "\", " << bbname << ");";
1460       break;
1461     }
1462     case Instruction::InsertValue: {
1463       const InsertValueInst *ivi = cast<InsertValueInst>(I);
1464       Out << "std::vector<unsigned> " << iName << "_indices;";
1465       nl(Out);
1466       for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1467         Out << iName << "_indices.push_back("
1468             << ivi->idx_begin()[i] << ");";
1469         nl(Out);
1470       }
1471       Out << "InsertValueInst* " << getCppName(ivi)
1472           << " = InsertValueInst::Create(" << opNames[0]
1473           << ", " << opNames[1] << ", "
1474           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1475       printEscapedString(ivi->getName());
1476       Out << "\", " << bbname << ");";
1477       break;
1478     }
1479   }
1480   DefinedValues.insert(I);
1481   nl(Out);
1482   delete [] opNames;
1483 }
1484
1485   // Print out the types, constants and declarations needed by one function
1486   void CppWriter::printFunctionUses(const Function* F) {
1487     nl(Out) << "// Type Definitions"; nl(Out);
1488     if (!is_inline) {
1489       // Print the function's return type
1490       printType(F->getReturnType());
1491
1492       // Print the function's function type
1493       printType(F->getFunctionType());
1494
1495       // Print the types of each of the function's arguments
1496       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1497            AI != AE; ++AI) {
1498         printType(AI->getType());
1499       }
1500     }
1501
1502     // Print type definitions for every type referenced by an instruction and
1503     // make a note of any global values or constants that are referenced
1504     SmallPtrSet<GlobalValue*,64> gvs;
1505     SmallPtrSet<Constant*,64> consts;
1506     for (Function::const_iterator BB = F->begin(), BE = F->end();
1507          BB != BE; ++BB){
1508       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1509            I != E; ++I) {
1510         // Print the type of the instruction itself
1511         printType(I->getType());
1512
1513         // Print the type of each of the instruction's operands
1514         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1515           Value* operand = I->getOperand(i);
1516           printType(operand->getType());
1517
1518           // If the operand references a GVal or Constant, make a note of it
1519           if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1520             gvs.insert(GV);
1521             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1522               if (GVar->hasInitializer())
1523                 consts.insert(GVar->getInitializer());
1524           } else if (Constant* C = dyn_cast<Constant>(operand))
1525             consts.insert(C);
1526         }
1527       }
1528     }
1529
1530     // Print the function declarations for any functions encountered
1531     nl(Out) << "// Function Declarations"; nl(Out);
1532     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1533          I != E; ++I) {
1534       if (Function* Fun = dyn_cast<Function>(*I)) {
1535         if (!is_inline || Fun != F)
1536           printFunctionHead(Fun);
1537       }
1538     }
1539
1540     // Print the global variable declarations for any variables encountered
1541     nl(Out) << "// Global Variable Declarations"; nl(Out);
1542     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1543          I != E; ++I) {
1544       if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1545         printVariableHead(F);
1546     }
1547
1548   // Print the constants found
1549     nl(Out) << "// Constant Definitions"; nl(Out);
1550     for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1551            E = consts.end(); I != E; ++I) {
1552       printConstant(*I);
1553     }
1554
1555     // Process the global variables definitions now that all the constants have
1556     // been emitted. These definitions just couple the gvars with their constant
1557     // initializers.
1558     nl(Out) << "// Global Variable Definitions"; nl(Out);
1559     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1560          I != E; ++I) {
1561       if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1562         printVariableBody(GV);
1563     }
1564   }
1565
1566   void CppWriter::printFunctionHead(const Function* F) {
1567     nl(Out) << "Function* " << getCppName(F);
1568     if (is_inline) {
1569       Out << " = mod->getFunction(\"";
1570       printEscapedString(F->getName());
1571       Out << "\", " << getCppName(F->getFunctionType()) << ");";
1572       nl(Out) << "if (!" << getCppName(F) << ") {";
1573       nl(Out) << getCppName(F);
1574     }
1575     Out<< " = Function::Create(";
1576     nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1577     nl(Out) << "/*Linkage=*/";
1578     printLinkageType(F->getLinkage());
1579     Out << ",";
1580     nl(Out) << "/*Name=*/\"";
1581     printEscapedString(F->getName());
1582     Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1583     nl(Out,-1);
1584     printCppName(F);
1585     Out << "->setCallingConv(";
1586     printCallingConv(F->getCallingConv());
1587     Out << ");";
1588     nl(Out);
1589     if (F->hasSection()) {
1590       printCppName(F);
1591       Out << "->setSection(\"" << F->getSection() << "\");";
1592       nl(Out);
1593     }
1594     if (F->getAlignment()) {
1595       printCppName(F);
1596       Out << "->setAlignment(" << F->getAlignment() << ");";
1597       nl(Out);
1598     }
1599     if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1600       printCppName(F);
1601       Out << "->setVisibility(";
1602       printVisibilityType(F->getVisibility());
1603       Out << ");";
1604       nl(Out);
1605     }
1606     if (F->hasCollector()) {
1607       printCppName(F);
1608       Out << "->setCollector(\"" << F->getCollector() << "\");";
1609       nl(Out);
1610     }
1611     if (is_inline) {
1612       Out << "}";
1613       nl(Out);
1614     }
1615     printParamAttrs(F->getParamAttrs(), getCppName(F));
1616     printCppName(F);
1617     Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1618     nl(Out);
1619   }
1620
1621   void CppWriter::printFunctionBody(const Function *F) {
1622     if (F->isDeclaration())
1623       return; // external functions have no bodies.
1624
1625     // Clear the DefinedValues and ForwardRefs maps because we can't have
1626     // cross-function forward refs
1627     ForwardRefs.clear();
1628     DefinedValues.clear();
1629
1630     // Create all the argument values
1631     if (!is_inline) {
1632       if (!F->arg_empty()) {
1633         Out << "Function::arg_iterator args = " << getCppName(F)
1634             << "->arg_begin();";
1635         nl(Out);
1636       }
1637       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1638            AI != AE; ++AI) {
1639         Out << "Value* " << getCppName(AI) << " = args++;";
1640         nl(Out);
1641         if (AI->hasName()) {
1642           Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1643           nl(Out);
1644         }
1645       }
1646     }
1647
1648     // Create all the basic blocks
1649     nl(Out);
1650     for (Function::const_iterator BI = F->begin(), BE = F->end();
1651          BI != BE; ++BI) {
1652       std::string bbname(getCppName(BI));
1653       Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1654       if (BI->hasName())
1655         printEscapedString(BI->getName());
1656       Out << "\"," << getCppName(BI->getParent()) << ",0);";
1657       nl(Out);
1658     }
1659
1660     // Output all of its basic blocks... for the function
1661     for (Function::const_iterator BI = F->begin(), BE = F->end();
1662          BI != BE; ++BI) {
1663       std::string bbname(getCppName(BI));
1664       nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1665       nl(Out);
1666
1667       // Output all of the instructions in the basic block...
1668       for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1669            I != E; ++I) {
1670         printInstruction(I,bbname);
1671       }
1672     }
1673
1674     // Loop over the ForwardRefs and resolve them now that all instructions
1675     // are generated.
1676     if (!ForwardRefs.empty()) {
1677       nl(Out) << "// Resolve Forward References";
1678       nl(Out);
1679     }
1680
1681     while (!ForwardRefs.empty()) {
1682       ForwardRefMap::iterator I = ForwardRefs.begin();
1683       Out << I->second << "->replaceAllUsesWith("
1684           << getCppName(I->first) << "); delete " << I->second << ";";
1685       nl(Out);
1686       ForwardRefs.erase(I);
1687     }
1688   }
1689
1690   void CppWriter::printInline(const std::string& fname,
1691                               const std::string& func) {
1692     const Function* F = TheModule->getFunction(func);
1693     if (!F) {
1694       error(std::string("Function '") + func + "' not found in input module");
1695       return;
1696     }
1697     if (F->isDeclaration()) {
1698       error(std::string("Function '") + func + "' is external!");
1699       return;
1700     }
1701     nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1702             << getCppName(F);
1703     unsigned arg_count = 1;
1704     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1705          AI != AE; ++AI) {
1706       Out << ", Value* arg_" << arg_count;
1707     }
1708     Out << ") {";
1709     nl(Out);
1710     is_inline = true;
1711     printFunctionUses(F);
1712     printFunctionBody(F);
1713     is_inline = false;
1714     Out << "return " << getCppName(F->begin()) << ";";
1715     nl(Out) << "}";
1716     nl(Out);
1717   }
1718
1719   void CppWriter::printModuleBody() {
1720     // Print out all the type definitions
1721     nl(Out) << "// Type Definitions"; nl(Out);
1722     printTypes(TheModule);
1723
1724     // Functions can call each other and global variables can reference them so
1725     // define all the functions first before emitting their function bodies.
1726     nl(Out) << "// Function Declarations"; nl(Out);
1727     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1728          I != E; ++I)
1729       printFunctionHead(I);
1730
1731     // Process the global variables declarations. We can't initialze them until
1732     // after the constants are printed so just print a header for each global
1733     nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1734     for (Module::const_global_iterator I = TheModule->global_begin(),
1735            E = TheModule->global_end(); I != E; ++I) {
1736       printVariableHead(I);
1737     }
1738
1739     // Print out all the constants definitions. Constants don't recurse except
1740     // through GlobalValues. All GlobalValues have been declared at this point
1741     // so we can proceed to generate the constants.
1742     nl(Out) << "// Constant Definitions"; nl(Out);
1743     printConstants(TheModule);
1744
1745     // Process the global variables definitions now that all the constants have
1746     // been emitted. These definitions just couple the gvars with their constant
1747     // initializers.
1748     nl(Out) << "// Global Variable Definitions"; nl(Out);
1749     for (Module::const_global_iterator I = TheModule->global_begin(),
1750            E = TheModule->global_end(); I != E; ++I) {
1751       printVariableBody(I);
1752     }
1753
1754     // Finally, we can safely put out all of the function bodies.
1755     nl(Out) << "// Function Definitions"; nl(Out);
1756     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1757          I != E; ++I) {
1758       if (!I->isDeclaration()) {
1759         nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1760                 << ")";
1761         nl(Out) << "{";
1762         nl(Out,1);
1763         printFunctionBody(I);
1764         nl(Out,-1) << "}";
1765         nl(Out);
1766       }
1767     }
1768   }
1769
1770   void CppWriter::printProgram(const std::string& fname,
1771                                const std::string& mName) {
1772     Out << "#include <llvm/Module.h>\n";
1773     Out << "#include <llvm/DerivedTypes.h>\n";
1774     Out << "#include <llvm/Constants.h>\n";
1775     Out << "#include <llvm/GlobalVariable.h>\n";
1776     Out << "#include <llvm/Function.h>\n";
1777     Out << "#include <llvm/CallingConv.h>\n";
1778     Out << "#include <llvm/BasicBlock.h>\n";
1779     Out << "#include <llvm/Instructions.h>\n";
1780     Out << "#include <llvm/InlineAsm.h>\n";
1781     Out << "#include <llvm/Support/MathExtras.h>\n";
1782     Out << "#include <llvm/Pass.h>\n";
1783     Out << "#include <llvm/PassManager.h>\n";
1784     Out << "#include <llvm/ADT/SmallVector.h>\n";
1785     Out << "#include <llvm/Analysis/Verifier.h>\n";
1786     Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1787     Out << "#include <algorithm>\n";
1788     Out << "#include <iostream>\n\n";
1789     Out << "using namespace llvm;\n\n";
1790     Out << "Module* " << fname << "();\n\n";
1791     Out << "int main(int argc, char**argv) {\n";
1792     Out << "  Module* Mod = " << fname << "();\n";
1793     Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1794     Out << "  std::cerr.flush();\n";
1795     Out << "  std::cout.flush();\n";
1796     Out << "  PassManager PM;\n";
1797     Out << "  PM.add(new PrintModulePass(&llvm::cout));\n";
1798     Out << "  PM.run(*Mod);\n";
1799     Out << "  return 0;\n";
1800     Out << "}\n\n";
1801     printModule(fname,mName);
1802   }
1803
1804   void CppWriter::printModule(const std::string& fname,
1805                               const std::string& mName) {
1806     nl(Out) << "Module* " << fname << "() {";
1807     nl(Out,1) << "// Module Construction";
1808     nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1809     if (!TheModule->getTargetTriple().empty()) {
1810       nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1811     }
1812     if (!TheModule->getTargetTriple().empty()) {
1813       nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1814               << "\");";
1815     }
1816
1817     if (!TheModule->getModuleInlineAsm().empty()) {
1818       nl(Out) << "mod->setModuleInlineAsm(\"";
1819       printEscapedString(TheModule->getModuleInlineAsm());
1820       Out << "\");";
1821     }
1822     nl(Out);
1823
1824     // Loop over the dependent libraries and emit them.
1825     Module::lib_iterator LI = TheModule->lib_begin();
1826     Module::lib_iterator LE = TheModule->lib_end();
1827     while (LI != LE) {
1828       Out << "mod->addLibrary(\"" << *LI << "\");";
1829       nl(Out);
1830       ++LI;
1831     }
1832     printModuleBody();
1833     nl(Out) << "return mod;";
1834     nl(Out,-1) << "}";
1835     nl(Out);
1836   }
1837
1838   void CppWriter::printContents(const std::string& fname,
1839                                 const std::string& mName) {
1840     Out << "\nModule* " << fname << "(Module *mod) {\n";
1841     Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1842     printModuleBody();
1843     Out << "\nreturn mod;\n";
1844     Out << "\n}\n";
1845   }
1846
1847   void CppWriter::printFunction(const std::string& fname,
1848                                 const std::string& funcName) {
1849     const Function* F = TheModule->getFunction(funcName);
1850     if (!F) {
1851       error(std::string("Function '") + funcName + "' not found in input module");
1852       return;
1853     }
1854     Out << "\nFunction* " << fname << "(Module *mod) {\n";
1855     printFunctionUses(F);
1856     printFunctionHead(F);
1857     printFunctionBody(F);
1858     Out << "return " << getCppName(F) << ";\n";
1859     Out << "}\n";
1860   }
1861
1862   void CppWriter::printFunctions() {
1863     const Module::FunctionListType &funcs = TheModule->getFunctionList();
1864     Module::const_iterator I  = funcs.begin();
1865     Module::const_iterator IE = funcs.end();
1866
1867     for (; I != IE; ++I) {
1868       const Function &func = *I;
1869       if (!func.isDeclaration()) {
1870         std::string name("define_");
1871         name += func.getName();
1872         printFunction(name, func.getName());
1873       }
1874     }
1875   }
1876
1877   void CppWriter::printVariable(const std::string& fname,
1878                                 const std::string& varName) {
1879     const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1880
1881     if (!GV) {
1882       error(std::string("Variable '") + varName + "' not found in input module");
1883       return;
1884     }
1885     Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1886     printVariableUses(GV);
1887     printVariableHead(GV);
1888     printVariableBody(GV);
1889     Out << "return " << getCppName(GV) << ";\n";
1890     Out << "}\n";
1891   }
1892
1893   void CppWriter::printType(const std::string& fname,
1894                             const std::string& typeName) {
1895     const Type* Ty = TheModule->getTypeByName(typeName);
1896     if (!Ty) {
1897       error(std::string("Type '") + typeName + "' not found in input module");
1898       return;
1899     }
1900     Out << "\nType* " << fname << "(Module *mod) {\n";
1901     printType(Ty);
1902     Out << "return " << getCppName(Ty) << ";\n";
1903     Out << "}\n";
1904   }
1905
1906   bool CppWriter::runOnModule(Module &M) {
1907     TheModule = &M;
1908
1909     // Emit a header
1910     Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1911
1912     // Get the name of the function we're supposed to generate
1913     std::string fname = FuncName.getValue();
1914
1915     // Get the name of the thing we are to generate
1916     std::string tgtname = NameToGenerate.getValue();
1917     if (GenerationType == GenModule ||
1918         GenerationType == GenContents ||
1919         GenerationType == GenProgram ||
1920         GenerationType == GenFunctions) {
1921       if (tgtname == "!bad!") {
1922         if (M.getModuleIdentifier() == "-")
1923           tgtname = "<stdin>";
1924         else
1925           tgtname = M.getModuleIdentifier();
1926       }
1927     } else if (tgtname == "!bad!")
1928       error("You must use the -for option with -gen-{function,variable,type}");
1929
1930     switch (WhatToGenerate(GenerationType)) {
1931      case GenProgram:
1932       if (fname.empty())
1933         fname = "makeLLVMModule";
1934       printProgram(fname,tgtname);
1935       break;
1936      case GenModule:
1937       if (fname.empty())
1938         fname = "makeLLVMModule";
1939       printModule(fname,tgtname);
1940       break;
1941      case GenContents:
1942       if (fname.empty())
1943         fname = "makeLLVMModuleContents";
1944       printContents(fname,tgtname);
1945       break;
1946      case GenFunction:
1947       if (fname.empty())
1948         fname = "makeLLVMFunction";
1949       printFunction(fname,tgtname);
1950       break;
1951      case GenFunctions:
1952       printFunctions();
1953       break;
1954      case GenInline:
1955       if (fname.empty())
1956         fname = "makeLLVMInline";
1957       printInline(fname,tgtname);
1958       break;
1959      case GenVariable:
1960       if (fname.empty())
1961         fname = "makeLLVMVariable";
1962       printVariable(fname,tgtname);
1963       break;
1964      case GenType:
1965       if (fname.empty())
1966         fname = "makeLLVMType";
1967       printType(fname,tgtname);
1968       break;
1969      default:
1970       error("Invalid generation option");
1971     }
1972
1973     return false;
1974   }
1975 }
1976
1977 char CppWriter::ID = 0;
1978
1979 //===----------------------------------------------------------------------===//
1980 //                       External Interface declaration
1981 //===----------------------------------------------------------------------===//
1982
1983 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1984                                                 std::ostream &o,
1985                                                 CodeGenFileType FileType,
1986                                                 bool Fast) {
1987   if (FileType != TargetMachine::AssemblyFile) return true;
1988   PM.add(new CppWriter(o));
1989   return false;
1990 }