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