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