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