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