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