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