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