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