assert(0) -> LLVM_UNREACHABLE.
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Streams.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Config/config.h"
35 #include <algorithm>
36 #include <set>
37
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
42          cl::value_desc("function name"));
43
44 enum WhatToGenerate {
45   GenProgram,
46   GenModule,
47   GenContents,
48   GenFunction,
49   GenFunctions,
50   GenInline,
51   GenVariable,
52   GenType
53 };
54
55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
56   cl::desc("Choose what kind of output to generate"),
57   cl::init(GenProgram),
58   cl::values(
59     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
60     clEnumValN(GenModule,   "module",    "Generate a module definition"),
61     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
62     clEnumValN(GenFunction, "function",  "Generate a function definition"),
63     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
65     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
66     clEnumValN(GenType,     "type",      "Generate a type definition"),
67     clEnumValEnd
68   )
69 );
70
71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
72   cl::desc("Specify the name of the thing to generate"),
73   cl::init("!bad!"));
74
75 /// CppBackendTargetMachineModule - Note that this is used on hosts
76 /// that cannot link in a library unless there are references into the
77 /// library.  In particular, it seems that it is not possible to get
78 /// things to work on Win32 without this.  Though it is unused, do not
79 /// remove it.
80 extern "C" int CppBackendTargetMachineModule;
81 int CppBackendTargetMachineModule = 0;
82
83 // Register the target.
84 static RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend");
85
86 // Force static initialization.
87 extern "C" void LLVMInitializeCppBackendTarget() { }
88
89 namespace {
90   typedef std::vector<const Type*> TypeList;
91   typedef std::map<const Type*,std::string> TypeMap;
92   typedef std::map<const Value*,std::string> ValueMap;
93   typedef std::set<std::string> NameSet;
94   typedef std::set<const Type*> TypeSet;
95   typedef std::set<const Value*> ValueSet;
96   typedef std::map<const Value*,std::string> ForwardRefMap;
97
98   /// CppWriter - This class is the main chunk of code that converts an LLVM
99   /// module to a C++ translation unit.
100   class CppWriter : public ModulePass {
101     raw_ostream &Out;
102     const Module *TheModule;
103     uint64_t uniqueNum;
104     TypeMap TypeNames;
105     ValueMap ValueNames;
106     TypeMap UnresolvedTypes;
107     TypeList TypeStack;
108     NameSet UsedNames;
109     TypeSet DefinedTypes;
110     ValueSet DefinedValues;
111     ForwardRefMap ForwardRefs;
112     bool is_inline;
113
114   public:
115     static char ID;
116     explicit CppWriter(raw_ostream &o) :
117       ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
118
119     virtual const char *getPassName() const { return "C++ backend"; }
120
121     bool runOnModule(Module &M);
122
123     void printProgram(const std::string& fname, const std::string& modName );
124     void printModule(const std::string& fname, const std::string& modName );
125     void printContents(const std::string& fname, const std::string& modName );
126     void printFunction(const std::string& fname, const std::string& funcName );
127     void printFunctions();
128     void printInline(const std::string& fname, const std::string& funcName );
129     void printVariable(const std::string& fname, const std::string& varName );
130     void printType(const std::string& fname, const std::string& typeName );
131
132     void error(const std::string& msg);
133
134   private:
135     void printLinkageType(GlobalValue::LinkageTypes LT);
136     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
137     void printCallingConv(unsigned 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
168   static unsigned indent_level = 0;
169   inline raw_ostream& nl(raw_ostream& Out, int delta = 0) {
170     Out << "\n";
171     if (delta >= 0 || indent_level >= unsigned(-delta))
172       indent_level += delta;
173     for (unsigned i = 0; i < indent_level; ++i)
174       Out << "  ";
175     return Out;
176   }
177
178   inline void in() { indent_level++; }
179   inline void out() { if (indent_level >0) indent_level--; }
180
181   inline void
182   sanitize(std::string& str) {
183     for (size_t i = 0; i < str.length(); ++i)
184       if (!isalnum(str[i]) && str[i] != '_')
185         str[i] = '_';
186   }
187
188   inline std::string
189   getTypePrefix(const Type* Ty ) {
190     switch (Ty->getTypeID()) {
191     case Type::VoidTyID:     return "void_";
192     case Type::IntegerTyID:
193       return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
194         "_";
195     case Type::FloatTyID:    return "float_";
196     case Type::DoubleTyID:   return "double_";
197     case Type::LabelTyID:    return "label_";
198     case Type::FunctionTyID: return "func_";
199     case Type::StructTyID:   return "struct_";
200     case Type::ArrayTyID:    return "array_";
201     case Type::PointerTyID:  return "ptr_";
202     case Type::VectorTyID:   return "packed_";
203     case Type::OpaqueTyID:   return "opaque_";
204     default:                 return "other_";
205     }
206     return "unknown_";
207   }
208
209   // Looks up the type in the symbol table and returns a pointer to its name or
210   // a null pointer if it wasn't found. Note that this isn't the same as the
211   // Mode::getTypeName function which will return an empty string, not a null
212   // pointer if the name is not found.
213   inline const std::string*
214   findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
215     TypeSymbolTable::const_iterator TI = ST.begin();
216     TypeSymbolTable::const_iterator TE = ST.end();
217     for (;TI != TE; ++TI)
218       if (TI->second == Ty)
219         return &(TI->first);
220     return 0;
221   }
222
223   void CppWriter::error(const std::string& msg) {
224     llvm_report_error(msg);
225   }
226
227   // printCFP - Print a floating point constant .. very carefully :)
228   // This makes sure that conversion to/from floating yields the same binary
229   // result so that we don't lose precision.
230   void CppWriter::printCFP(const ConstantFP *CFP) {
231     bool ignored;
232     APFloat APF = APFloat(CFP->getValueAPF());  // copy
233     if (CFP->getType() == Type::FloatTy)
234       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
235     Out << "ConstantFP::get(";
236     Out << "APFloat(";
237 #if HAVE_PRINTF_A
238     char Buffer[100];
239     sprintf(Buffer, "%A", APF.convertToDouble());
240     if ((!strncmp(Buffer, "0x", 2) ||
241          !strncmp(Buffer, "-0x", 3) ||
242          !strncmp(Buffer, "+0x", 3)) &&
243         APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
244       if (CFP->getType() == Type::DoubleTy)
245         Out << "BitsToDouble(" << Buffer << ")";
246       else
247         Out << "BitsToFloat((float)" << Buffer << ")";
248       Out << ")";
249     } else {
250 #endif
251       std::string StrVal = ftostr(CFP->getValueAPF());
252
253       while (StrVal[0] == ' ')
254         StrVal.erase(StrVal.begin());
255
256       // Check to make sure that the stringized number is not some string like
257       // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
258       if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
259            ((StrVal[0] == '-' || StrVal[0] == '+') &&
260             (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
261           (CFP->isExactlyValue(atof(StrVal.c_str())))) {
262         if (CFP->getType() == Type::DoubleTy)
263           Out <<  StrVal;
264         else
265           Out << StrVal << "f";
266       } else if (CFP->getType() == Type::DoubleTy)
267         Out << "BitsToDouble(0x"
268             << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
269             << "ULL) /* " << StrVal << " */";
270       else
271         Out << "BitsToFloat(0x"
272             << utohexstr((uint32_t)CFP->getValueAPF().
273                                         bitcastToAPInt().getZExtValue())
274             << "U) /* " << StrVal << " */";
275       Out << ")";
276 #if HAVE_PRINTF_A
277     }
278 #endif
279     Out << ")";
280   }
281
282   void CppWriter::printCallingConv(unsigned cc){
283     // Print the calling convention.
284     switch (cc) {
285     case CallingConv::C:     Out << "CallingConv::C"; break;
286     case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
287     case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
288     case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
289     default:                 Out << cc; break;
290     }
291   }
292
293   void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
294     switch (LT) {
295     case GlobalValue::InternalLinkage:
296       Out << "GlobalValue::InternalLinkage"; break;
297     case GlobalValue::PrivateLinkage:
298       Out << "GlobalValue::PrivateLinkage"; break;
299     case GlobalValue::AvailableExternallyLinkage:
300       Out << "GlobalValue::AvailableExternallyLinkage "; break;
301     case GlobalValue::LinkOnceAnyLinkage:
302       Out << "GlobalValue::LinkOnceAnyLinkage "; break;
303     case GlobalValue::LinkOnceODRLinkage:
304       Out << "GlobalValue::LinkOnceODRLinkage "; break;
305     case GlobalValue::WeakAnyLinkage:
306       Out << "GlobalValue::WeakAnyLinkage"; break;
307     case GlobalValue::WeakODRLinkage:
308       Out << "GlobalValue::WeakODRLinkage"; break;
309     case GlobalValue::AppendingLinkage:
310       Out << "GlobalValue::AppendingLinkage"; break;
311     case GlobalValue::ExternalLinkage:
312       Out << "GlobalValue::ExternalLinkage"; break;
313     case GlobalValue::DLLImportLinkage:
314       Out << "GlobalValue::DLLImportLinkage"; break;
315     case GlobalValue::DLLExportLinkage:
316       Out << "GlobalValue::DLLExportLinkage"; break;
317     case GlobalValue::ExternalWeakLinkage:
318       Out << "GlobalValue::ExternalWeakLinkage"; break;
319     case GlobalValue::GhostLinkage:
320       Out << "GlobalValue::GhostLinkage"; break;
321     case GlobalValue::CommonLinkage:
322       Out << "GlobalValue::CommonLinkage"; break;
323     }
324   }
325
326   void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
327     switch (VisType) {
328     default: LLVM_UNREACHABLE("Unknown GVar visibility");
329     case GlobalValue::DefaultVisibility:
330       Out << "GlobalValue::DefaultVisibility";
331       break;
332     case GlobalValue::HiddenVisibility:
333       Out << "GlobalValue::HiddenVisibility";
334       break;
335     case GlobalValue::ProtectedVisibility:
336       Out << "GlobalValue::ProtectedVisibility";
337       break;
338     }
339   }
340
341   // printEscapedString - Print each character of the specified string, escaping
342   // it if it is not printable or if it is an escape char.
343   void CppWriter::printEscapedString(const std::string &Str) {
344     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
345       unsigned char C = Str[i];
346       if (isprint(C) && C != '"' && C != '\\') {
347         Out << C;
348       } else {
349         Out << "\\x"
350             << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
351             << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
352       }
353     }
354   }
355
356   std::string CppWriter::getCppName(const Type* Ty) {
357     // First, handle the primitive types .. easy
358     if (Ty->isPrimitiveType() || Ty->isInteger()) {
359       switch (Ty->getTypeID()) {
360       case Type::VoidTyID:   return "Type::VoidTy";
361       case Type::IntegerTyID: {
362         unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
363         return "IntegerType::get(" + utostr(BitWidth) + ")";
364       }
365       case Type::X86_FP80TyID: return "Type::X86_FP80Ty";
366       case Type::FloatTyID:    return "Type::FloatTy";
367       case Type::DoubleTyID:   return "Type::DoubleTy";
368       case Type::LabelTyID:    return "Type::LabelTy";
369       default:
370         error("Invalid primitive type");
371         break;
372       }
373       return "Type::VoidTy"; // shouldn't be returned, but make it sensible
374     }
375
376     // Now, see if we've seen the type before and return that
377     TypeMap::iterator I = TypeNames.find(Ty);
378     if (I != TypeNames.end())
379       return I->second;
380
381     // Okay, let's build a new name for this type. Start with a prefix
382     const char* prefix = 0;
383     switch (Ty->getTypeID()) {
384     case Type::FunctionTyID:    prefix = "FuncTy_"; break;
385     case Type::StructTyID:      prefix = "StructTy_"; break;
386     case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
387     case Type::PointerTyID:     prefix = "PointerTy_"; break;
388     case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
389     case Type::VectorTyID:      prefix = "VectorTy_"; break;
390     default:                    prefix = "OtherTy_"; break; // prevent breakage
391     }
392
393     // See if the type has a name in the symboltable and build accordingly
394     const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
395     std::string name;
396     if (tName)
397       name = std::string(prefix) + *tName;
398     else
399       name = std::string(prefix) + utostr(uniqueNum++);
400     sanitize(name);
401
402     // Save the name
403     return TypeNames[Ty] = name;
404   }
405
406   void CppWriter::printCppName(const Type* Ty) {
407     printEscapedString(getCppName(Ty));
408   }
409
410   std::string CppWriter::getCppName(const Value* val) {
411     std::string name;
412     ValueMap::iterator I = ValueNames.find(val);
413     if (I != ValueNames.end() && I->first == val)
414       return  I->second;
415
416     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
417       name = std::string("gvar_") +
418         getTypePrefix(GV->getType()->getElementType());
419     } else if (isa<Function>(val)) {
420       name = std::string("func_");
421     } else if (const Constant* C = dyn_cast<Constant>(val)) {
422       name = std::string("const_") + getTypePrefix(C->getType());
423     } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
424       if (is_inline) {
425         unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
426                                         Function::const_arg_iterator(Arg)) + 1;
427         name = std::string("arg_") + utostr(argNum);
428         NameSet::iterator NI = UsedNames.find(name);
429         if (NI != UsedNames.end())
430           name += std::string("_") + utostr(uniqueNum++);
431         UsedNames.insert(name);
432         return ValueNames[val] = name;
433       } else {
434         name = getTypePrefix(val->getType());
435       }
436     } else {
437       name = getTypePrefix(val->getType());
438     }
439     name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
440     sanitize(name);
441     NameSet::iterator NI = UsedNames.find(name);
442     if (NI != UsedNames.end())
443       name += std::string("_") + utostr(uniqueNum++);
444     UsedNames.insert(name);
445     return ValueNames[val] = name;
446   }
447
448   void CppWriter::printCppName(const Value* val) {
449     printEscapedString(getCppName(val));
450   }
451
452   void CppWriter::printAttributes(const AttrListPtr &PAL,
453                                   const std::string &name) {
454     Out << "AttrListPtr " << name << "_PAL;";
455     nl(Out);
456     if (!PAL.isEmpty()) {
457       Out << '{'; in(); nl(Out);
458       Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
459       Out << "AttributeWithIndex PAWI;"; nl(Out);
460       for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
461         unsigned index = PAL.getSlot(i).Index;
462         Attributes attrs = PAL.getSlot(i).Attrs;
463         Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
464 #define HANDLE_ATTR(X)                 \
465         if (attrs & Attribute::X)      \
466           Out << " | Attribute::" #X;  \
467         attrs &= ~Attribute::X;
468         
469         HANDLE_ATTR(SExt);
470         HANDLE_ATTR(ZExt);
471         HANDLE_ATTR(NoReturn);
472         HANDLE_ATTR(InReg);
473         HANDLE_ATTR(StructRet);
474         HANDLE_ATTR(NoUnwind);
475         HANDLE_ATTR(NoAlias);
476         HANDLE_ATTR(ByVal);
477         HANDLE_ATTR(Nest);
478         HANDLE_ATTR(ReadNone);
479         HANDLE_ATTR(ReadOnly);
480         HANDLE_ATTR(NoInline);
481         HANDLE_ATTR(AlwaysInline);
482         HANDLE_ATTR(OptimizeForSize);
483         HANDLE_ATTR(StackProtect);
484         HANDLE_ATTR(StackProtectReq);
485         HANDLE_ATTR(NoCapture);
486 #undef HANDLE_ATTR
487         assert(attrs == 0 && "Unhandled attribute!");
488         Out << ";";
489         nl(Out);
490         Out << "Attrs.push_back(PAWI);";
491         nl(Out);
492       }
493       Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
494       nl(Out);
495       out(); nl(Out);
496       Out << '}'; nl(Out);
497     }
498   }
499
500   bool CppWriter::printTypeInternal(const Type* Ty) {
501     // We don't print definitions for primitive types
502     if (Ty->isPrimitiveType() || Ty->isInteger())
503       return false;
504
505     // If we already defined this type, we don't need to define it again.
506     if (DefinedTypes.find(Ty) != DefinedTypes.end())
507       return false;
508
509     // Everything below needs the name for the type so get it now.
510     std::string typeName(getCppName(Ty));
511
512     // Search the type stack for recursion. If we find it, then generate this
513     // as an OpaqueType, but make sure not to do this multiple times because
514     // the type could appear in multiple places on the stack. Once the opaque
515     // definition is issued, it must not be re-issued. Consequently we have to
516     // check the UnresolvedTypes list as well.
517     TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
518                                             Ty);
519     if (TI != TypeStack.end()) {
520       TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
521       if (I == UnresolvedTypes.end()) {
522         Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
523         nl(Out);
524         UnresolvedTypes[Ty] = typeName;
525       }
526       return true;
527     }
528
529     // We're going to print a derived type which, by definition, contains other
530     // types. So, push this one we're printing onto the type stack to assist with
531     // recursive definitions.
532     TypeStack.push_back(Ty);
533
534     // Print the type definition
535     switch (Ty->getTypeID()) {
536     case Type::FunctionTyID:  {
537       const FunctionType* FT = cast<FunctionType>(Ty);
538       Out << "std::vector<const Type*>" << typeName << "_args;";
539       nl(Out);
540       FunctionType::param_iterator PI = FT->param_begin();
541       FunctionType::param_iterator PE = FT->param_end();
542       for (; PI != PE; ++PI) {
543         const Type* argTy = static_cast<const Type*>(*PI);
544         bool isForward = printTypeInternal(argTy);
545         std::string argName(getCppName(argTy));
546         Out << typeName << "_args.push_back(" << argName;
547         if (isForward)
548           Out << "_fwd";
549         Out << ");";
550         nl(Out);
551       }
552       bool isForward = printTypeInternal(FT->getReturnType());
553       std::string retTypeName(getCppName(FT->getReturnType()));
554       Out << "FunctionType* " << typeName << " = FunctionType::get(";
555       in(); nl(Out) << "/*Result=*/" << retTypeName;
556       if (isForward)
557         Out << "_fwd";
558       Out << ",";
559       nl(Out) << "/*Params=*/" << typeName << "_args,";
560       nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
561       out();
562       nl(Out);
563       break;
564     }
565     case Type::StructTyID: {
566       const StructType* ST = cast<StructType>(Ty);
567       Out << "std::vector<const Type*>" << typeName << "_fields;";
568       nl(Out);
569       StructType::element_iterator EI = ST->element_begin();
570       StructType::element_iterator EE = ST->element_end();
571       for (; EI != EE; ++EI) {
572         const Type* fieldTy = static_cast<const Type*>(*EI);
573         bool isForward = printTypeInternal(fieldTy);
574         std::string fieldName(getCppName(fieldTy));
575         Out << typeName << "_fields.push_back(" << fieldName;
576         if (isForward)
577           Out << "_fwd";
578         Out << ");";
579         nl(Out);
580       }
581       Out << "StructType* " << typeName << " = StructType::get("
582           << typeName << "_fields, /*isPacked=*/"
583           << (ST->isPacked() ? "true" : "false") << ");";
584       nl(Out);
585       break;
586     }
587     case Type::ArrayTyID: {
588       const ArrayType* AT = cast<ArrayType>(Ty);
589       const Type* ET = AT->getElementType();
590       bool isForward = printTypeInternal(ET);
591       std::string elemName(getCppName(ET));
592       Out << "ArrayType* " << typeName << " = ArrayType::get("
593           << elemName << (isForward ? "_fwd" : "")
594           << ", " << utostr(AT->getNumElements()) << ");";
595       nl(Out);
596       break;
597     }
598     case Type::PointerTyID: {
599       const PointerType* PT = cast<PointerType>(Ty);
600       const Type* ET = PT->getElementType();
601       bool isForward = printTypeInternal(ET);
602       std::string elemName(getCppName(ET));
603       Out << "PointerType* " << typeName << " = PointerType::get("
604           << elemName << (isForward ? "_fwd" : "")
605           << ", " << utostr(PT->getAddressSpace()) << ");";
606       nl(Out);
607       break;
608     }
609     case Type::VectorTyID: {
610       const VectorType* PT = cast<VectorType>(Ty);
611       const Type* ET = PT->getElementType();
612       bool isForward = printTypeInternal(ET);
613       std::string elemName(getCppName(ET));
614       Out << "VectorType* " << typeName << " = VectorType::get("
615           << elemName << (isForward ? "_fwd" : "")
616           << ", " << utostr(PT->getNumElements()) << ");";
617       nl(Out);
618       break;
619     }
620     case Type::OpaqueTyID: {
621       Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
622       nl(Out);
623       break;
624     }
625     default:
626       error("Invalid TypeID");
627     }
628
629     // If the type had a name, make sure we recreate it.
630     const std::string* progTypeName =
631       findTypeName(TheModule->getTypeSymbolTable(),Ty);
632     if (progTypeName) {
633       Out << "mod->addTypeName(\"" << *progTypeName << "\", "
634           << typeName << ");";
635       nl(Out);
636     }
637
638     // Pop us off the type stack
639     TypeStack.pop_back();
640
641     // Indicate that this type is now defined.
642     DefinedTypes.insert(Ty);
643
644     // Early resolve as many unresolved types as possible. Search the unresolved
645     // types map for the type we just printed. Now that its definition is complete
646     // we can resolve any previous references to it. This prevents a cascade of
647     // unresolved types.
648     TypeMap::iterator I = UnresolvedTypes.find(Ty);
649     if (I != UnresolvedTypes.end()) {
650       Out << "cast<OpaqueType>(" << I->second
651           << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
652       nl(Out);
653       Out << I->second << " = cast<";
654       switch (Ty->getTypeID()) {
655       case Type::FunctionTyID: Out << "FunctionType"; break;
656       case Type::ArrayTyID:    Out << "ArrayType"; break;
657       case Type::StructTyID:   Out << "StructType"; break;
658       case Type::VectorTyID:   Out << "VectorType"; break;
659       case Type::PointerTyID:  Out << "PointerType"; break;
660       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
661       default:                 Out << "NoSuchDerivedType"; break;
662       }
663       Out << ">(" << I->second << "_fwd.get());";
664       nl(Out); nl(Out);
665       UnresolvedTypes.erase(I);
666     }
667
668     // Finally, separate the type definition from other with a newline.
669     nl(Out);
670
671     // We weren't a recursive type
672     return false;
673   }
674
675   // Prints a type definition. Returns true if it could not resolve all the
676   // types in the definition but had to use a forward reference.
677   void CppWriter::printType(const Type* Ty) {
678     assert(TypeStack.empty());
679     TypeStack.clear();
680     printTypeInternal(Ty);
681     assert(TypeStack.empty());
682   }
683
684   void CppWriter::printTypes(const Module* M) {
685     // Walk the symbol table and print out all its types
686     const TypeSymbolTable& symtab = M->getTypeSymbolTable();
687     for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
688          TI != TE; ++TI) {
689
690       // For primitive types and types already defined, just add a name
691       TypeMap::const_iterator TNI = TypeNames.find(TI->second);
692       if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
693           TNI != TypeNames.end()) {
694         Out << "mod->addTypeName(\"";
695         printEscapedString(TI->first);
696         Out << "\", " << getCppName(TI->second) << ");";
697         nl(Out);
698         // For everything else, define the type
699       } else {
700         printType(TI->second);
701       }
702     }
703
704     // Add all of the global variables to the value table...
705     for (Module::const_global_iterator I = TheModule->global_begin(),
706            E = TheModule->global_end(); I != E; ++I) {
707       if (I->hasInitializer())
708         printType(I->getInitializer()->getType());
709       printType(I->getType());
710     }
711
712     // Add all the functions to the table
713     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
714          FI != FE; ++FI) {
715       printType(FI->getReturnType());
716       printType(FI->getFunctionType());
717       // Add all the function arguments
718       for (Function::const_arg_iterator AI = FI->arg_begin(),
719              AE = FI->arg_end(); AI != AE; ++AI) {
720         printType(AI->getType());
721       }
722
723       // Add all of the basic blocks and instructions
724       for (Function::const_iterator BB = FI->begin(),
725              E = FI->end(); BB != E; ++BB) {
726         printType(BB->getType());
727         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
728              ++I) {
729           printType(I->getType());
730           for (unsigned i = 0; i < I->getNumOperands(); ++i)
731             printType(I->getOperand(i)->getType());
732         }
733       }
734     }
735   }
736
737
738   // printConstant - Print out a constant pool entry...
739   void CppWriter::printConstant(const Constant *CV) {
740     // First, if the constant is actually a GlobalValue (variable or function)
741     // or its already in the constant list then we've printed it already and we
742     // can just return.
743     if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
744       return;
745
746     std::string constName(getCppName(CV));
747     std::string typeName(getCppName(CV->getType()));
748
749     if (isa<GlobalValue>(CV)) {
750       // Skip variables and functions, we emit them elsewhere
751       return;
752     }
753
754     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
755       std::string constValue = CI->getValue().toString(10, true);
756       Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
757           << cast<IntegerType>(CI->getType())->getBitWidth() << ",  \""
758           <<  constValue << "\", " << constValue.length() << ", 10));";
759     } else if (isa<ConstantAggregateZero>(CV)) {
760       Out << "ConstantAggregateZero* " << constName
761           << " = ConstantAggregateZero::get(" << typeName << ");";
762     } else if (isa<ConstantPointerNull>(CV)) {
763       Out << "ConstantPointerNull* " << constName
764           << " = ConstantPointerNull::get(" << typeName << ");";
765     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
766       Out << "ConstantFP* " << constName << " = ";
767       printCFP(CFP);
768       Out << ";";
769     } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
770       if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
771         Out << "Constant* " << constName << " = ConstantArray::get(\"";
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       } else  {
985         nl(Out) << "// Constant Definitions"; nl(Out);
986         printConstant(gv);
987       }
988       if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
989         nl(Out) << "// Global Variable Definitions"; nl(Out);
990         printVariableBody(gv);
991       }
992     }
993   }
994
995   void CppWriter::printVariableHead(const GlobalVariable *GV) {
996     nl(Out) << "GlobalVariable* " << getCppName(GV);
997     if (is_inline) {
998       Out << " = mod->getGlobalVariable(";
999       printEscapedString(GV->getName());
1000       Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1001       nl(Out) << "if (!" << getCppName(GV) << ") {";
1002       in(); nl(Out) << getCppName(GV);
1003     }
1004     Out << " = new GlobalVariable(/*Module=*/*mod";
1005     nl(Out) << "/*Type=*/";
1006     printCppName(GV->getType()->getElementType());
1007     Out << ",";
1008     nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1009     Out << ",";
1010     nl(Out) << "/*Linkage=*/";
1011     printLinkageType(GV->getLinkage());
1012     Out << ",";
1013     nl(Out) << "/*Initializer=*/0, ";
1014     if (GV->hasInitializer()) {
1015       Out << "// has initializer, specified below";
1016     }
1017     nl(Out) << "/*Name=*/\"";
1018     printEscapedString(GV->getName());
1019     Out << "\");";
1020     nl(Out);
1021
1022     if (GV->hasSection()) {
1023       printCppName(GV);
1024       Out << "->setSection(\"";
1025       printEscapedString(GV->getSection());
1026       Out << "\");";
1027       nl(Out);
1028     }
1029     if (GV->getAlignment()) {
1030       printCppName(GV);
1031       Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1032       nl(Out);
1033     }
1034     if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1035       printCppName(GV);
1036       Out << "->setVisibility(";
1037       printVisibilityType(GV->getVisibility());
1038       Out << ");";
1039       nl(Out);
1040     }
1041     if (is_inline) {
1042       out(); Out << "}"; nl(Out);
1043     }
1044   }
1045
1046   void CppWriter::printVariableBody(const GlobalVariable *GV) {
1047     if (GV->hasInitializer()) {
1048       printCppName(GV);
1049       Out << "->setInitializer(";
1050       Out << getCppName(GV->getInitializer()) << ");";
1051       nl(Out);
1052     }
1053   }
1054
1055   std::string CppWriter::getOpName(Value* V) {
1056     if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1057       return getCppName(V);
1058
1059     // See if its alread in the map of forward references, if so just return the
1060     // name we already set up for it
1061     ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1062     if (I != ForwardRefs.end())
1063       return I->second;
1064
1065     // This is a new forward reference. Generate a unique name for it
1066     std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1067
1068     // Yes, this is a hack. An Argument is the smallest instantiable value that
1069     // we can make as a placeholder for the real value. We'll replace these
1070     // Argument instances later.
1071     Out << "Argument* " << result << " = new Argument("
1072         << getCppName(V->getType()) << ");";
1073     nl(Out);
1074     ForwardRefs[V] = result;
1075     return result;
1076   }
1077
1078   // printInstruction - This member is called for each Instruction in a function.
1079   void CppWriter::printInstruction(const Instruction *I,
1080                                    const std::string& bbname) {
1081     std::string iName(getCppName(I));
1082
1083     // Before we emit this instruction, we need to take care of generating any
1084     // forward references. So, we get the names of all the operands in advance
1085     std::string* opNames = new std::string[I->getNumOperands()];
1086     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1087       opNames[i] = getOpName(I->getOperand(i));
1088     }
1089
1090     switch (I->getOpcode()) {
1091     default:
1092       error("Invalid instruction");
1093       break;
1094
1095     case Instruction::Ret: {
1096       const ReturnInst* ret =  cast<ReturnInst>(I);
1097       Out << "ReturnInst::Create("
1098           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1099       break;
1100     }
1101     case Instruction::Br: {
1102       const BranchInst* br = cast<BranchInst>(I);
1103       Out << "BranchInst::Create(" ;
1104       if (br->getNumOperands() == 3 ) {
1105         Out << opNames[2] << ", "
1106             << opNames[1] << ", "
1107             << opNames[0] << ", ";
1108
1109       } else if (br->getNumOperands() == 1) {
1110         Out << opNames[0] << ", ";
1111       } else {
1112         error("Branch with 2 operands?");
1113       }
1114       Out << bbname << ");";
1115       break;
1116     }
1117     case Instruction::Switch: {
1118       const SwitchInst* sw = cast<SwitchInst>(I);
1119       Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1120           << opNames[0] << ", "
1121           << opNames[1] << ", "
1122           << sw->getNumCases() << ", " << bbname << ");";
1123       nl(Out);
1124       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1125         Out << iName << "->addCase("
1126             << opNames[i] << ", "
1127             << opNames[i+1] << ");";
1128         nl(Out);
1129       }
1130       break;
1131     }
1132     case Instruction::Invoke: {
1133       const InvokeInst* inv = cast<InvokeInst>(I);
1134       Out << "std::vector<Value*> " << iName << "_params;";
1135       nl(Out);
1136       for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1137         Out << iName << "_params.push_back("
1138             << opNames[i] << ");";
1139         nl(Out);
1140       }
1141       Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1142           << opNames[0] << ", "
1143           << opNames[1] << ", "
1144           << opNames[2] << ", "
1145           << iName << "_params.begin(), " << iName << "_params.end(), \"";
1146       printEscapedString(inv->getName());
1147       Out << "\", " << bbname << ");";
1148       nl(Out) << iName << "->setCallingConv(";
1149       printCallingConv(inv->getCallingConv());
1150       Out << ");";
1151       printAttributes(inv->getAttributes(), iName);
1152       Out << iName << "->setAttributes(" << iName << "_PAL);";
1153       nl(Out);
1154       break;
1155     }
1156     case Instruction::Unwind: {
1157       Out << "new UnwindInst("
1158           << bbname << ");";
1159       break;
1160     }
1161     case Instruction::Unreachable:{
1162       Out << "new UnreachableInst("
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(";
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 << "\", " << bbname << ");";
1235       break;
1236     }
1237     case Instruction::ICmp: {
1238       Out << "ICmpInst* " << iName << " = new ICmpInst(";
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 << "\", " << bbname << ");";
1255       break;
1256     }
1257     case Instruction::Malloc: {
1258       const MallocInst* mallocI = cast<MallocInst>(I);
1259       Out << "MallocInst* " << iName << " = new MallocInst("
1260           << getCppName(mallocI->getAllocatedType()) << ", ";
1261       if (mallocI->isArrayAllocation())
1262         Out << opNames[0] << ", " ;
1263       Out << "\"";
1264       printEscapedString(mallocI->getName());
1265       Out << "\", " << bbname << ");";
1266       if (mallocI->getAlignment())
1267         nl(Out) << iName << "->setAlignment("
1268             << mallocI->getAlignment() << ");";
1269       break;
1270     }
1271     case Instruction::Free: {
1272       Out << "FreeInst* " << iName << " = new FreeInst("
1273           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
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 << " = BasicBlock::Create(\"";
1683       if (BI->hasName())
1684         printEscapedString(BI->getName());
1685       Out << "\"," << getCppName(BI->getParent()) << ",0);";
1686       nl(Out);
1687     }
1688
1689     // Output all of its basic blocks... for the function
1690     for (Function::const_iterator BI = F->begin(), BE = F->end();
1691          BI != BE; ++BI) {
1692       std::string bbname(getCppName(BI));
1693       nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1694       nl(Out);
1695
1696       // Output all of the instructions in the basic block...
1697       for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1698            I != E; ++I) {
1699         printInstruction(I,bbname);
1700       }
1701     }
1702
1703     // Loop over the ForwardRefs and resolve them now that all instructions
1704     // are generated.
1705     if (!ForwardRefs.empty()) {
1706       nl(Out) << "// Resolve Forward References";
1707       nl(Out);
1708     }
1709
1710     while (!ForwardRefs.empty()) {
1711       ForwardRefMap::iterator I = ForwardRefs.begin();
1712       Out << I->second << "->replaceAllUsesWith("
1713           << getCppName(I->first) << "); delete " << I->second << ";";
1714       nl(Out);
1715       ForwardRefs.erase(I);
1716     }
1717   }
1718
1719   void CppWriter::printInline(const std::string& fname,
1720                               const std::string& func) {
1721     const Function* F = TheModule->getFunction(func);
1722     if (!F) {
1723       error(std::string("Function '") + func + "' not found in input module");
1724       return;
1725     }
1726     if (F->isDeclaration()) {
1727       error(std::string("Function '") + func + "' is external!");
1728       return;
1729     }
1730     nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1731             << getCppName(F);
1732     unsigned arg_count = 1;
1733     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1734          AI != AE; ++AI) {
1735       Out << ", Value* arg_" << arg_count;
1736     }
1737     Out << ") {";
1738     nl(Out);
1739     is_inline = true;
1740     printFunctionUses(F);
1741     printFunctionBody(F);
1742     is_inline = false;
1743     Out << "return " << getCppName(F->begin()) << ";";
1744     nl(Out) << "}";
1745     nl(Out);
1746   }
1747
1748   void CppWriter::printModuleBody() {
1749     // Print out all the type definitions
1750     nl(Out) << "// Type Definitions"; nl(Out);
1751     printTypes(TheModule);
1752
1753     // Functions can call each other and global variables can reference them so
1754     // define all the functions first before emitting their function bodies.
1755     nl(Out) << "// Function Declarations"; nl(Out);
1756     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1757          I != E; ++I)
1758       printFunctionHead(I);
1759
1760     // Process the global variables declarations. We can't initialze them until
1761     // after the constants are printed so just print a header for each global
1762     nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1763     for (Module::const_global_iterator I = TheModule->global_begin(),
1764            E = TheModule->global_end(); I != E; ++I) {
1765       printVariableHead(I);
1766     }
1767
1768     // Print out all the constants definitions. Constants don't recurse except
1769     // through GlobalValues. All GlobalValues have been declared at this point
1770     // so we can proceed to generate the constants.
1771     nl(Out) << "// Constant Definitions"; nl(Out);
1772     printConstants(TheModule);
1773
1774     // Process the global variables definitions now that all the constants have
1775     // been emitted. These definitions just couple the gvars with their constant
1776     // initializers.
1777     nl(Out) << "// Global Variable Definitions"; nl(Out);
1778     for (Module::const_global_iterator I = TheModule->global_begin(),
1779            E = TheModule->global_end(); I != E; ++I) {
1780       printVariableBody(I);
1781     }
1782
1783     // Finally, we can safely put out all of the function bodies.
1784     nl(Out) << "// Function Definitions"; nl(Out);
1785     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1786          I != E; ++I) {
1787       if (!I->isDeclaration()) {
1788         nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1789                 << ")";
1790         nl(Out) << "{";
1791         nl(Out,1);
1792         printFunctionBody(I);
1793         nl(Out,-1) << "}";
1794         nl(Out);
1795       }
1796     }
1797   }
1798
1799   void CppWriter::printProgram(const std::string& fname,
1800                                const std::string& mName) {
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/MathExtras.h>\n";
1811     Out << "#include <llvm/Support/raw_ostream.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 << "  outs().flush();\n";
1824     Out << "  PassManager PM;\n";
1825     Out << "  PM.add(createPrintModulePass(&outs()));\n";
1826     Out << "  PM.run(*Mod);\n";
1827     Out << "  return 0;\n";
1828     Out << "}\n\n";
1829     printModule(fname,mName);
1830   }
1831
1832   void CppWriter::printModule(const std::string& fname,
1833                               const std::string& mName) {
1834     nl(Out) << "Module* " << fname << "() {";
1835     nl(Out,1) << "// Module Construction";
1836     nl(Out) << "Module* mod = new Module(\"";
1837     printEscapedString(mName);
1838     Out << "\");";
1839     if (!TheModule->getTargetTriple().empty()) {
1840       nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1841     }
1842     if (!TheModule->getTargetTriple().empty()) {
1843       nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1844               << "\");";
1845     }
1846
1847     if (!TheModule->getModuleInlineAsm().empty()) {
1848       nl(Out) << "mod->setModuleInlineAsm(\"";
1849       printEscapedString(TheModule->getModuleInlineAsm());
1850       Out << "\");";
1851     }
1852     nl(Out);
1853
1854     // Loop over the dependent libraries and emit them.
1855     Module::lib_iterator LI = TheModule->lib_begin();
1856     Module::lib_iterator LE = TheModule->lib_end();
1857     while (LI != LE) {
1858       Out << "mod->addLibrary(\"" << *LI << "\");";
1859       nl(Out);
1860       ++LI;
1861     }
1862     printModuleBody();
1863     nl(Out) << "return mod;";
1864     nl(Out,-1) << "}";
1865     nl(Out);
1866   }
1867
1868   void CppWriter::printContents(const std::string& fname,
1869                                 const std::string& mName) {
1870     Out << "\nModule* " << fname << "(Module *mod) {\n";
1871     Out << "\nmod->setModuleIdentifier(\"";
1872     printEscapedString(mName);
1873     Out << "\");\n";
1874     printModuleBody();
1875     Out << "\nreturn mod;\n";
1876     Out << "\n}\n";
1877   }
1878
1879   void CppWriter::printFunction(const std::string& fname,
1880                                 const std::string& funcName) {
1881     const Function* F = TheModule->getFunction(funcName);
1882     if (!F) {
1883       error(std::string("Function '") + funcName + "' not found in input module");
1884       return;
1885     }
1886     Out << "\nFunction* " << fname << "(Module *mod) {\n";
1887     printFunctionUses(F);
1888     printFunctionHead(F);
1889     printFunctionBody(F);
1890     Out << "return " << getCppName(F) << ";\n";
1891     Out << "}\n";
1892   }
1893
1894   void CppWriter::printFunctions() {
1895     const Module::FunctionListType &funcs = TheModule->getFunctionList();
1896     Module::const_iterator I  = funcs.begin();
1897     Module::const_iterator IE = funcs.end();
1898
1899     for (; I != IE; ++I) {
1900       const Function &func = *I;
1901       if (!func.isDeclaration()) {
1902         std::string name("define_");
1903         name += func.getName();
1904         printFunction(name, func.getName());
1905       }
1906     }
1907   }
1908
1909   void CppWriter::printVariable(const std::string& fname,
1910                                 const std::string& varName) {
1911     const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1912
1913     if (!GV) {
1914       error(std::string("Variable '") + varName + "' not found in input module");
1915       return;
1916     }
1917     Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1918     printVariableUses(GV);
1919     printVariableHead(GV);
1920     printVariableBody(GV);
1921     Out << "return " << getCppName(GV) << ";\n";
1922     Out << "}\n";
1923   }
1924
1925   void CppWriter::printType(const std::string& fname,
1926                             const std::string& typeName) {
1927     const Type* Ty = TheModule->getTypeByName(typeName);
1928     if (!Ty) {
1929       error(std::string("Type '") + typeName + "' not found in input module");
1930       return;
1931     }
1932     Out << "\nType* " << fname << "(Module *mod) {\n";
1933     printType(Ty);
1934     Out << "return " << getCppName(Ty) << ";\n";
1935     Out << "}\n";
1936   }
1937
1938   bool CppWriter::runOnModule(Module &M) {
1939     TheModule = &M;
1940
1941     // Emit a header
1942     Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1943
1944     // Get the name of the function we're supposed to generate
1945     std::string fname = FuncName.getValue();
1946
1947     // Get the name of the thing we are to generate
1948     std::string tgtname = NameToGenerate.getValue();
1949     if (GenerationType == GenModule ||
1950         GenerationType == GenContents ||
1951         GenerationType == GenProgram ||
1952         GenerationType == GenFunctions) {
1953       if (tgtname == "!bad!") {
1954         if (M.getModuleIdentifier() == "-")
1955           tgtname = "<stdin>";
1956         else
1957           tgtname = M.getModuleIdentifier();
1958       }
1959     } else if (tgtname == "!bad!")
1960       error("You must use the -for option with -gen-{function,variable,type}");
1961
1962     switch (WhatToGenerate(GenerationType)) {
1963      case GenProgram:
1964       if (fname.empty())
1965         fname = "makeLLVMModule";
1966       printProgram(fname,tgtname);
1967       break;
1968      case GenModule:
1969       if (fname.empty())
1970         fname = "makeLLVMModule";
1971       printModule(fname,tgtname);
1972       break;
1973      case GenContents:
1974       if (fname.empty())
1975         fname = "makeLLVMModuleContents";
1976       printContents(fname,tgtname);
1977       break;
1978      case GenFunction:
1979       if (fname.empty())
1980         fname = "makeLLVMFunction";
1981       printFunction(fname,tgtname);
1982       break;
1983      case GenFunctions:
1984       printFunctions();
1985       break;
1986      case GenInline:
1987       if (fname.empty())
1988         fname = "makeLLVMInline";
1989       printInline(fname,tgtname);
1990       break;
1991      case GenVariable:
1992       if (fname.empty())
1993         fname = "makeLLVMVariable";
1994       printVariable(fname,tgtname);
1995       break;
1996      case GenType:
1997       if (fname.empty())
1998         fname = "makeLLVMType";
1999       printType(fname,tgtname);
2000       break;
2001      default:
2002       error("Invalid generation option");
2003     }
2004
2005     return false;
2006   }
2007 }
2008
2009 char CppWriter::ID = 0;
2010
2011 //===----------------------------------------------------------------------===//
2012 //                       External Interface declaration
2013 //===----------------------------------------------------------------------===//
2014
2015 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2016                                                 raw_ostream &o,
2017                                                 CodeGenFileType FileType,
2018                                                 CodeGenOpt::Level OptLevel) {
2019   if (FileType != TargetMachine::AssemblyFile) return true;
2020   PM.add(new CppWriter(o));
2021   return false;
2022 }