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