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