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