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