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