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