LLVM  mainline
CPPBackend.cpp
Go to the documentation of this file.
00001 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the writing of the LLVM IR as a set of C++ calls to the
00011 // LLVM IR interface. The input module is assumed to be verified.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "CPPTargetMachine.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/Config/config.h"
00020 #include "llvm/IR/CallingConv.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/InlineAsm.h"
00024 #include "llvm/IR/Instruction.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/LegacyPassManager.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/MC/MCAsmInfo.h"
00029 #include "llvm/MC/MCInstrInfo.h"
00030 #include "llvm/MC/MCSubtargetInfo.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/FormattedStream.h"
00035 #include "llvm/Support/TargetRegistry.h"
00036 #include <algorithm>
00037 #include <cctype>
00038 #include <cstdio>
00039 #include <map>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 static cl::opt<std::string>
00044 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
00045          cl::value_desc("function name"));
00046 
00047 enum WhatToGenerate {
00048   GenProgram,
00049   GenModule,
00050   GenContents,
00051   GenFunction,
00052   GenFunctions,
00053   GenInline,
00054   GenVariable,
00055   GenType
00056 };
00057 
00058 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
00059   cl::desc("Choose what kind of output to generate"),
00060   cl::init(GenProgram),
00061   cl::values(
00062     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
00063     clEnumValN(GenModule,   "module",    "Generate a module definition"),
00064     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
00065     clEnumValN(GenFunction, "function",  "Generate a function definition"),
00066     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
00067     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
00068     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
00069     clEnumValN(GenType,     "type",      "Generate a type definition"),
00070     clEnumValEnd
00071   )
00072 );
00073 
00074 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
00075   cl::desc("Specify the name of the thing to generate"),
00076   cl::init("!bad!"));
00077 
00078 extern "C" void LLVMInitializeCppBackendTarget() {
00079   // Register the target.
00080   RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
00081 }
00082 
00083 namespace {
00084   typedef std::vector<Type*> TypeList;
00085   typedef std::map<Type*,std::string> TypeMap;
00086   typedef std::map<const Value*,std::string> ValueMap;
00087   typedef std::set<std::string> NameSet;
00088   typedef std::set<Type*> TypeSet;
00089   typedef std::set<const Value*> ValueSet;
00090   typedef std::map<const Value*,std::string> ForwardRefMap;
00091 
00092   /// CppWriter - This class is the main chunk of code that converts an LLVM
00093   /// module to a C++ translation unit.
00094   class CppWriter : public ModulePass {
00095     std::unique_ptr<formatted_raw_ostream> OutOwner;
00096     formatted_raw_ostream &Out;
00097     const Module *TheModule;
00098     uint64_t uniqueNum;
00099     TypeMap TypeNames;
00100     ValueMap ValueNames;
00101     NameSet UsedNames;
00102     TypeSet DefinedTypes;
00103     ValueSet DefinedValues;
00104     ForwardRefMap ForwardRefs;
00105     bool is_inline;
00106     unsigned indent_level;
00107 
00108   public:
00109     static char ID;
00110     explicit CppWriter(std::unique_ptr<formatted_raw_ostream> o)
00111         : ModulePass(ID), OutOwner(std::move(o)), Out(*OutOwner), uniqueNum(0),
00112           is_inline(false), indent_level(0) {}
00113 
00114     const char *getPassName() const override { return "C++ backend"; }
00115 
00116     bool runOnModule(Module &M) override;
00117 
00118     void printProgram(const std::string& fname, const std::string& modName );
00119     void printModule(const std::string& fname, const std::string& modName );
00120     void printContents(const std::string& fname, const std::string& modName );
00121     void printFunction(const std::string& fname, const std::string& funcName );
00122     void printFunctions();
00123     void printInline(const std::string& fname, const std::string& funcName );
00124     void printVariable(const std::string& fname, const std::string& varName );
00125     void printType(const std::string& fname, const std::string& typeName );
00126 
00127     void error(const std::string& msg);
00128 
00129     
00130     formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
00131     inline void in() { indent_level++; }
00132     inline void out() { if (indent_level >0) indent_level--; }
00133     
00134   private:
00135     void printLinkageType(GlobalValue::LinkageTypes LT);
00136     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
00137     void printDLLStorageClassType(GlobalValue::DLLStorageClassTypes DSCType);
00138     void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
00139     void printCallingConv(CallingConv::ID cc);
00140     void printEscapedString(const std::string& str);
00141     void printCFP(const ConstantFP* CFP);
00142 
00143     std::string getCppName(Type* val);
00144     inline void printCppName(Type* val);
00145 
00146     std::string getCppName(const Value* val);
00147     inline void printCppName(const Value* val);
00148 
00149     void printAttributes(const AttributeSet &PAL, const std::string &name);
00150     void printType(Type* Ty);
00151     void printTypes(const Module* M);
00152 
00153     void printConstant(const Constant *CPV);
00154     void printConstants(const Module* M);
00155 
00156     void printVariableUses(const GlobalVariable *GV);
00157     void printVariableHead(const GlobalVariable *GV);
00158     void printVariableBody(const GlobalVariable *GV);
00159 
00160     void printFunctionUses(const Function *F);
00161     void printFunctionHead(const Function *F);
00162     void printFunctionBody(const Function *F);
00163     void printInstruction(const Instruction *I, const std::string& bbname);
00164     std::string getOpName(const Value*);
00165 
00166     void printModuleBody();
00167   };
00168 } // end anonymous namespace.
00169 
00170 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
00171   Out << '\n';
00172   if (delta >= 0 || indent_level >= unsigned(-delta))
00173     indent_level += delta;
00174   Out.indent(indent_level);
00175   return Out;
00176 }
00177 
00178 static inline void sanitize(std::string &str) {
00179   for (size_t i = 0; i < str.length(); ++i)
00180     if (!isalnum(str[i]) && str[i] != '_')
00181       str[i] = '_';
00182 }
00183 
00184 static std::string getTypePrefix(Type *Ty) {
00185   switch (Ty->getTypeID()) {
00186   case Type::VoidTyID:     return "void_";
00187   case Type::IntegerTyID:
00188     return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
00189   case Type::FloatTyID:    return "float_";
00190   case Type::DoubleTyID:   return "double_";
00191   case Type::LabelTyID:    return "label_";
00192   case Type::FunctionTyID: return "func_";
00193   case Type::StructTyID:   return "struct_";
00194   case Type::ArrayTyID:    return "array_";
00195   case Type::PointerTyID:  return "ptr_";
00196   case Type::VectorTyID:   return "packed_";
00197   default:                 return "other_";
00198   }
00199 }
00200 
00201 void CppWriter::error(const std::string& msg) {
00202   report_fatal_error(msg);
00203 }
00204 
00205 static inline std::string ftostr(const APFloat& V) {
00206   std::string Buf;
00207   if (&V.getSemantics() == &APFloat::IEEEdouble) {
00208     raw_string_ostream(Buf) << V.convertToDouble();
00209     return Buf;
00210   } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
00211     raw_string_ostream(Buf) << (double)V.convertToFloat();
00212     return Buf;
00213   }
00214   return "<unknown format in ftostr>"; // error
00215 }
00216 
00217 // printCFP - Print a floating point constant .. very carefully :)
00218 // This makes sure that conversion to/from floating yields the same binary
00219 // result so that we don't lose precision.
00220 void CppWriter::printCFP(const ConstantFP *CFP) {
00221   bool ignored;
00222   APFloat APF = APFloat(CFP->getValueAPF());  // copy
00223   if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
00224     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
00225   Out << "ConstantFP::get(mod->getContext(), ";
00226   Out << "APFloat(";
00227 #if HAVE_PRINTF_A
00228   char Buffer[100];
00229   sprintf(Buffer, "%A", APF.convertToDouble());
00230   if ((!strncmp(Buffer, "0x", 2) ||
00231        !strncmp(Buffer, "-0x", 3) ||
00232        !strncmp(Buffer, "+0x", 3)) &&
00233       APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
00234     if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00235       Out << "BitsToDouble(" << Buffer << ")";
00236     else
00237       Out << "BitsToFloat((float)" << Buffer << ")";
00238     Out << ")";
00239   } else {
00240 #endif
00241     std::string StrVal = ftostr(CFP->getValueAPF());
00242 
00243     while (StrVal[0] == ' ')
00244       StrVal.erase(StrVal.begin());
00245 
00246     // Check to make sure that the stringized number is not some string like
00247     // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
00248     if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00249          ((StrVal[0] == '-' || StrVal[0] == '+') &&
00250           (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
00251         (CFP->isExactlyValue(atof(StrVal.c_str())))) {
00252       if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00253         Out <<  StrVal;
00254       else
00255         Out << StrVal << "f";
00256     } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00257       Out << "BitsToDouble(0x"
00258           << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
00259           << "ULL) /* " << StrVal << " */";
00260     else
00261       Out << "BitsToFloat(0x"
00262           << utohexstr((uint32_t)CFP->getValueAPF().
00263                                       bitcastToAPInt().getZExtValue())
00264           << "U) /* " << StrVal << " */";
00265     Out << ")";
00266 #if HAVE_PRINTF_A
00267   }
00268 #endif
00269   Out << ")";
00270 }
00271 
00272 void CppWriter::printCallingConv(CallingConv::ID cc){
00273   // Print the calling convention.
00274   switch (cc) {
00275   case CallingConv::C:     Out << "CallingConv::C"; break;
00276   case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
00277   case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
00278   case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
00279   default:                 Out << cc; break;
00280   }
00281 }
00282 
00283 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
00284   switch (LT) {
00285   case GlobalValue::InternalLinkage:
00286     Out << "GlobalValue::InternalLinkage"; break;
00287   case GlobalValue::PrivateLinkage:
00288     Out << "GlobalValue::PrivateLinkage"; break;
00289   case GlobalValue::AvailableExternallyLinkage:
00290     Out << "GlobalValue::AvailableExternallyLinkage "; break;
00291   case GlobalValue::LinkOnceAnyLinkage:
00292     Out << "GlobalValue::LinkOnceAnyLinkage "; break;
00293   case GlobalValue::LinkOnceODRLinkage:
00294     Out << "GlobalValue::LinkOnceODRLinkage "; break;
00295   case GlobalValue::WeakAnyLinkage:
00296     Out << "GlobalValue::WeakAnyLinkage"; break;
00297   case GlobalValue::WeakODRLinkage:
00298     Out << "GlobalValue::WeakODRLinkage"; break;
00299   case GlobalValue::AppendingLinkage:
00300     Out << "GlobalValue::AppendingLinkage"; break;
00301   case GlobalValue::ExternalLinkage:
00302     Out << "GlobalValue::ExternalLinkage"; break;
00303   case GlobalValue::ExternalWeakLinkage:
00304     Out << "GlobalValue::ExternalWeakLinkage"; break;
00305   case GlobalValue::CommonLinkage:
00306     Out << "GlobalValue::CommonLinkage"; break;
00307   }
00308 }
00309 
00310 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
00311   switch (VisType) {
00312   case GlobalValue::DefaultVisibility:
00313     Out << "GlobalValue::DefaultVisibility";
00314     break;
00315   case GlobalValue::HiddenVisibility:
00316     Out << "GlobalValue::HiddenVisibility";
00317     break;
00318   case GlobalValue::ProtectedVisibility:
00319     Out << "GlobalValue::ProtectedVisibility";
00320     break;
00321   }
00322 }
00323 
00324 void CppWriter::printDLLStorageClassType(
00325                                     GlobalValue::DLLStorageClassTypes DSCType) {
00326   switch (DSCType) {
00327   case GlobalValue::DefaultStorageClass:
00328     Out << "GlobalValue::DefaultStorageClass";
00329     break;
00330   case GlobalValue::DLLImportStorageClass:
00331     Out << "GlobalValue::DLLImportStorageClass";
00332     break;
00333   case GlobalValue::DLLExportStorageClass:
00334     Out << "GlobalValue::DLLExportStorageClass";
00335     break;
00336   }
00337 }
00338 
00339 void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
00340   switch (TLM) {
00341     case GlobalVariable::NotThreadLocal:
00342       Out << "GlobalVariable::NotThreadLocal";
00343       break;
00344     case GlobalVariable::GeneralDynamicTLSModel:
00345       Out << "GlobalVariable::GeneralDynamicTLSModel";
00346       break;
00347     case GlobalVariable::LocalDynamicTLSModel:
00348       Out << "GlobalVariable::LocalDynamicTLSModel";
00349       break;
00350     case GlobalVariable::InitialExecTLSModel:
00351       Out << "GlobalVariable::InitialExecTLSModel";
00352       break;
00353     case GlobalVariable::LocalExecTLSModel:
00354       Out << "GlobalVariable::LocalExecTLSModel";
00355       break;
00356   }
00357 }
00358 
00359 // printEscapedString - Print each character of the specified string, escaping
00360 // it if it is not printable or if it is an escape char.
00361 void CppWriter::printEscapedString(const std::string &Str) {
00362   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00363     unsigned char C = Str[i];
00364     if (isprint(C) && C != '"' && C != '\\') {
00365       Out << C;
00366     } else {
00367       Out << "\\x"
00368           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
00369           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00370     }
00371   }
00372 }
00373 
00374 std::string CppWriter::getCppName(Type* Ty) {
00375   switch (Ty->getTypeID()) {
00376   default:
00377     break;
00378   case Type::VoidTyID:
00379     return "Type::getVoidTy(mod->getContext())";
00380   case Type::IntegerTyID: {
00381     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
00382     return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
00383   }
00384   case Type::X86_FP80TyID:
00385     return "Type::getX86_FP80Ty(mod->getContext())";
00386   case Type::FloatTyID:
00387     return "Type::getFloatTy(mod->getContext())";
00388   case Type::DoubleTyID:
00389     return "Type::getDoubleTy(mod->getContext())";
00390   case Type::LabelTyID:
00391     return "Type::getLabelTy(mod->getContext())";
00392   case Type::X86_MMXTyID:
00393     return "Type::getX86_MMXTy(mod->getContext())";
00394   }
00395 
00396   // Now, see if we've seen the type before and return that
00397   TypeMap::iterator I = TypeNames.find(Ty);
00398   if (I != TypeNames.end())
00399     return I->second;
00400 
00401   // Okay, let's build a new name for this type. Start with a prefix
00402   const char* prefix = nullptr;
00403   switch (Ty->getTypeID()) {
00404   case Type::FunctionTyID:    prefix = "FuncTy_"; break;
00405   case Type::StructTyID:      prefix = "StructTy_"; break;
00406   case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
00407   case Type::PointerTyID:     prefix = "PointerTy_"; break;
00408   case Type::VectorTyID:      prefix = "VectorTy_"; break;
00409   default:                    prefix = "OtherTy_"; break; // prevent breakage
00410   }
00411 
00412   // See if the type has a name in the symboltable and build accordingly
00413   std::string name;
00414   if (StructType *STy = dyn_cast<StructType>(Ty))
00415     if (STy->hasName())
00416       name = STy->getName();
00417   
00418   if (name.empty())
00419     name = utostr(uniqueNum++);
00420   
00421   name = std::string(prefix) + name;
00422   sanitize(name);
00423 
00424   // Save the name
00425   return TypeNames[Ty] = name;
00426 }
00427 
00428 void CppWriter::printCppName(Type* Ty) {
00429   printEscapedString(getCppName(Ty));
00430 }
00431 
00432 std::string CppWriter::getCppName(const Value* val) {
00433   std::string name;
00434   ValueMap::iterator I = ValueNames.find(val);
00435   if (I != ValueNames.end() && I->first == val)
00436     return  I->second;
00437 
00438   if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
00439     name = std::string("gvar_") +
00440       getTypePrefix(GV->getType()->getElementType());
00441   } else if (isa<Function>(val)) {
00442     name = std::string("func_");
00443   } else if (const Constant* C = dyn_cast<Constant>(val)) {
00444     name = std::string("const_") + getTypePrefix(C->getType());
00445   } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
00446     if (is_inline) {
00447       unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
00448                                       Function::const_arg_iterator(Arg)) + 1;
00449       name = std::string("arg_") + utostr(argNum);
00450       NameSet::iterator NI = UsedNames.find(name);
00451       if (NI != UsedNames.end())
00452         name += std::string("_") + utostr(uniqueNum++);
00453       UsedNames.insert(name);
00454       return ValueNames[val] = name;
00455     } else {
00456       name = getTypePrefix(val->getType());
00457     }
00458   } else {
00459     name = getTypePrefix(val->getType());
00460   }
00461   if (val->hasName())
00462     name += val->getName();
00463   else
00464     name += utostr(uniqueNum++);
00465   sanitize(name);
00466   NameSet::iterator NI = UsedNames.find(name);
00467   if (NI != UsedNames.end())
00468     name += std::string("_") + utostr(uniqueNum++);
00469   UsedNames.insert(name);
00470   return ValueNames[val] = name;
00471 }
00472 
00473 void CppWriter::printCppName(const Value* val) {
00474   printEscapedString(getCppName(val));
00475 }
00476 
00477 void CppWriter::printAttributes(const AttributeSet &PAL,
00478                                 const std::string &name) {
00479   Out << "AttributeSet " << name << "_PAL;";
00480   nl(Out);
00481   if (!PAL.isEmpty()) {
00482     Out << '{'; in(); nl(Out);
00483     Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
00484     Out << "AttributeSet PAS;"; in(); nl(Out);
00485     for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
00486       unsigned index = PAL.getSlotIndex(i);
00487       AttrBuilder attrs(PAL.getSlotAttributes(i), index);
00488       Out << "{"; in(); nl(Out);
00489       Out << "AttrBuilder B;"; nl(Out);
00490 
00491 #define HANDLE_ATTR(X)                                                  \
00492       if (attrs.contains(Attribute::X)) {                               \
00493         Out << "B.addAttribute(Attribute::" #X ");"; nl(Out);           \
00494         attrs.removeAttribute(Attribute::X);                            \
00495       }
00496 
00497       HANDLE_ATTR(SExt);
00498       HANDLE_ATTR(ZExt);
00499       HANDLE_ATTR(NoReturn);
00500       HANDLE_ATTR(InReg);
00501       HANDLE_ATTR(StructRet);
00502       HANDLE_ATTR(NoUnwind);
00503       HANDLE_ATTR(NoAlias);
00504       HANDLE_ATTR(ByVal);
00505       HANDLE_ATTR(InAlloca);
00506       HANDLE_ATTR(Nest);
00507       HANDLE_ATTR(ReadNone);
00508       HANDLE_ATTR(ReadOnly);
00509       HANDLE_ATTR(NoInline);
00510       HANDLE_ATTR(AlwaysInline);
00511       HANDLE_ATTR(OptimizeNone);
00512       HANDLE_ATTR(OptimizeForSize);
00513       HANDLE_ATTR(StackProtect);
00514       HANDLE_ATTR(StackProtectReq);
00515       HANDLE_ATTR(StackProtectStrong);
00516       HANDLE_ATTR(SafeStack);
00517       HANDLE_ATTR(NoCapture);
00518       HANDLE_ATTR(NoRedZone);
00519       HANDLE_ATTR(NoImplicitFloat);
00520       HANDLE_ATTR(Naked);
00521       HANDLE_ATTR(InlineHint);
00522       HANDLE_ATTR(ReturnsTwice);
00523       HANDLE_ATTR(UWTable);
00524       HANDLE_ATTR(NonLazyBind);
00525       HANDLE_ATTR(MinSize);
00526 #undef HANDLE_ATTR
00527 
00528       if (attrs.contains(Attribute::StackAlignment)) {
00529         Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
00530         nl(Out);
00531         attrs.removeAttribute(Attribute::StackAlignment);
00532       }
00533 
00534       Out << "PAS = AttributeSet::get(mod->getContext(), ";
00535       if (index == ~0U)
00536         Out << "~0U,";
00537       else
00538         Out << index << "U,";
00539       Out << " B);"; out(); nl(Out);
00540       Out << "}"; out(); nl(Out);
00541       nl(Out);
00542       Out << "Attrs.push_back(PAS);"; nl(Out);
00543     }
00544     Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
00545     nl(Out);
00546     out(); nl(Out);
00547     Out << '}'; nl(Out);
00548   }
00549 }
00550 
00551 void CppWriter::printType(Type* Ty) {
00552   // We don't print definitions for primitive types
00553   if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() ||
00554       Ty->isLabelTy() || Ty->isMetadataTy() || Ty->isVoidTy())
00555     return;
00556 
00557   // If we already defined this type, we don't need to define it again.
00558   if (DefinedTypes.find(Ty) != DefinedTypes.end())
00559     return;
00560 
00561   // Everything below needs the name for the type so get it now.
00562   std::string typeName(getCppName(Ty));
00563 
00564   // Print the type definition
00565   switch (Ty->getTypeID()) {
00566   case Type::FunctionTyID:  {
00567     FunctionType* FT = cast<FunctionType>(Ty);
00568     Out << "std::vector<Type*>" << typeName << "_args;";
00569     nl(Out);
00570     FunctionType::param_iterator PI = FT->param_begin();
00571     FunctionType::param_iterator PE = FT->param_end();
00572     for (; PI != PE; ++PI) {
00573       Type* argTy = static_cast<Type*>(*PI);
00574       printType(argTy);
00575       std::string argName(getCppName(argTy));
00576       Out << typeName << "_args.push_back(" << argName;
00577       Out << ");";
00578       nl(Out);
00579     }
00580     printType(FT->getReturnType());
00581     std::string retTypeName(getCppName(FT->getReturnType()));
00582     Out << "FunctionType* " << typeName << " = FunctionType::get(";
00583     in(); nl(Out) << "/*Result=*/" << retTypeName;
00584     Out << ",";
00585     nl(Out) << "/*Params=*/" << typeName << "_args,";
00586     nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
00587     out();
00588     nl(Out);
00589     break;
00590   }
00591   case Type::StructTyID: {
00592     StructType* ST = cast<StructType>(Ty);
00593     if (!ST->isLiteral()) {
00594       Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
00595       printEscapedString(ST->getName());
00596       Out << "\");";
00597       nl(Out);
00598       Out << "if (!" << typeName << ") {";
00599       nl(Out);
00600       Out << typeName << " = ";
00601       Out << "StructType::create(mod->getContext(), \"";
00602       printEscapedString(ST->getName());
00603       Out << "\");";
00604       nl(Out);
00605       Out << "}";
00606       nl(Out);
00607       // Indicate that this type is now defined.
00608       DefinedTypes.insert(Ty);
00609     }
00610 
00611     Out << "std::vector<Type*>" << typeName << "_fields;";
00612     nl(Out);
00613     StructType::element_iterator EI = ST->element_begin();
00614     StructType::element_iterator EE = ST->element_end();
00615     for (; EI != EE; ++EI) {
00616       Type* fieldTy = static_cast<Type*>(*EI);
00617       printType(fieldTy);
00618       std::string fieldName(getCppName(fieldTy));
00619       Out << typeName << "_fields.push_back(" << fieldName;
00620       Out << ");";
00621       nl(Out);
00622     }
00623 
00624     if (ST->isLiteral()) {
00625       Out << "StructType *" << typeName << " = ";
00626       Out << "StructType::get(" << "mod->getContext(), ";
00627     } else {
00628       Out << "if (" << typeName << "->isOpaque()) {";
00629       nl(Out);
00630       Out << typeName << "->setBody(";
00631     }
00632 
00633     Out << typeName << "_fields, /*isPacked=*/"
00634         << (ST->isPacked() ? "true" : "false") << ");";
00635     nl(Out);
00636     if (!ST->isLiteral()) {
00637       Out << "}";
00638       nl(Out);
00639     }
00640     break;
00641   }
00642   case Type::ArrayTyID: {
00643     ArrayType* AT = cast<ArrayType>(Ty);
00644     Type* ET = AT->getElementType();
00645     printType(ET);
00646     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00647       std::string elemName(getCppName(ET));
00648       Out << "ArrayType* " << typeName << " = ArrayType::get("
00649           << elemName << ", " << AT->getNumElements() << ");";
00650       nl(Out);
00651     }
00652     break;
00653   }
00654   case Type::PointerTyID: {
00655     PointerType* PT = cast<PointerType>(Ty);
00656     Type* ET = PT->getElementType();
00657     printType(ET);
00658     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00659       std::string elemName(getCppName(ET));
00660       Out << "PointerType* " << typeName << " = PointerType::get("
00661           << elemName << ", " << PT->getAddressSpace() << ");";
00662       nl(Out);
00663     }
00664     break;
00665   }
00666   case Type::VectorTyID: {
00667     VectorType* PT = cast<VectorType>(Ty);
00668     Type* ET = PT->getElementType();
00669     printType(ET);
00670     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00671       std::string elemName(getCppName(ET));
00672       Out << "VectorType* " << typeName << " = VectorType::get("
00673           << elemName << ", " << PT->getNumElements() << ");";
00674       nl(Out);
00675     }
00676     break;
00677   }
00678   default:
00679     error("Invalid TypeID");
00680   }
00681 
00682   // Indicate that this type is now defined.
00683   DefinedTypes.insert(Ty);
00684 
00685   // Finally, separate the type definition from other with a newline.
00686   nl(Out);
00687 }
00688 
00689 void CppWriter::printTypes(const Module* M) {
00690   // Add all of the global variables to the value table.
00691   for (Module::const_global_iterator I = TheModule->global_begin(),
00692          E = TheModule->global_end(); I != E; ++I) {
00693     if (I->hasInitializer())
00694       printType(I->getInitializer()->getType());
00695     printType(I->getType());
00696   }
00697 
00698   // Add all the functions to the table
00699   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00700        FI != FE; ++FI) {
00701     printType(FI->getReturnType());
00702     printType(FI->getFunctionType());
00703     // Add all the function arguments
00704     for (Function::const_arg_iterator AI = FI->arg_begin(),
00705            AE = FI->arg_end(); AI != AE; ++AI) {
00706       printType(AI->getType());
00707     }
00708 
00709     // Add all of the basic blocks and instructions
00710     for (Function::const_iterator BB = FI->begin(),
00711            E = FI->end(); BB != E; ++BB) {
00712       printType(BB->getType());
00713       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00714            ++I) {
00715         printType(I->getType());
00716         for (unsigned i = 0; i < I->getNumOperands(); ++i)
00717           printType(I->getOperand(i)->getType());
00718       }
00719     }
00720   }
00721 }
00722 
00723 
00724 // printConstant - Print out a constant pool entry...
00725 void CppWriter::printConstant(const Constant *CV) {
00726   // First, if the constant is actually a GlobalValue (variable or function)
00727   // or its already in the constant list then we've printed it already and we
00728   // can just return.
00729   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
00730     return;
00731 
00732   std::string constName(getCppName(CV));
00733   std::string typeName(getCppName(CV->getType()));
00734 
00735   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00736     std::string constValue = CI->getValue().toString(10, true);
00737     Out << "ConstantInt* " << constName
00738         << " = ConstantInt::get(mod->getContext(), APInt("
00739         << cast<IntegerType>(CI->getType())->getBitWidth()
00740         << ", StringRef(\"" <<  constValue << "\"), 10));";
00741   } else if (isa<ConstantAggregateZero>(CV)) {
00742     Out << "ConstantAggregateZero* " << constName
00743         << " = ConstantAggregateZero::get(" << typeName << ");";
00744   } else if (isa<ConstantPointerNull>(CV)) {
00745     Out << "ConstantPointerNull* " << constName
00746         << " = ConstantPointerNull::get(" << typeName << ");";
00747   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00748     Out << "ConstantFP* " << constName << " = ";
00749     printCFP(CFP);
00750     Out << ";";
00751   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
00752     Out << "std::vector<Constant*> " << constName << "_elems;";
00753     nl(Out);
00754     unsigned N = CA->getNumOperands();
00755     for (unsigned i = 0; i < N; ++i) {
00756       printConstant(CA->getOperand(i)); // recurse to print operands
00757       Out << constName << "_elems.push_back("
00758           << getCppName(CA->getOperand(i)) << ");";
00759       nl(Out);
00760     }
00761     Out << "Constant* " << constName << " = ConstantArray::get("
00762         << typeName << ", " << constName << "_elems);";
00763   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
00764     Out << "std::vector<Constant*> " << constName << "_fields;";
00765     nl(Out);
00766     unsigned N = CS->getNumOperands();
00767     for (unsigned i = 0; i < N; i++) {
00768       printConstant(CS->getOperand(i));
00769       Out << constName << "_fields.push_back("
00770           << getCppName(CS->getOperand(i)) << ");";
00771       nl(Out);
00772     }
00773     Out << "Constant* " << constName << " = ConstantStruct::get("
00774         << typeName << ", " << constName << "_fields);";
00775   } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
00776     Out << "std::vector<Constant*> " << constName << "_elems;";
00777     nl(Out);
00778     unsigned N = CVec->getNumOperands();
00779     for (unsigned i = 0; i < N; ++i) {
00780       printConstant(CVec->getOperand(i));
00781       Out << constName << "_elems.push_back("
00782           << getCppName(CVec->getOperand(i)) << ");";
00783       nl(Out);
00784     }
00785     Out << "Constant* " << constName << " = ConstantVector::get("
00786         << typeName << ", " << constName << "_elems);";
00787   } else if (isa<UndefValue>(CV)) {
00788     Out << "UndefValue* " << constName << " = UndefValue::get("
00789         << typeName << ");";
00790   } else if (const ConstantDataSequential *CDS =
00791                dyn_cast<ConstantDataSequential>(CV)) {
00792     if (CDS->isString()) {
00793       Out << "Constant *" << constName <<
00794       " = ConstantDataArray::getString(mod->getContext(), \"";
00795       StringRef Str = CDS->getAsString();
00796       bool nullTerminate = false;
00797       if (Str.back() == 0) {
00798         Str = Str.drop_back();
00799         nullTerminate = true;
00800       }
00801       printEscapedString(Str);
00802       // Determine if we want null termination or not.
00803       if (nullTerminate)
00804         Out << "\", true);";
00805       else
00806         Out << "\", false);";// No null terminator
00807     } else {
00808       // TODO: Could generate more efficient code generating CDS calls instead.
00809       Out << "std::vector<Constant*> " << constName << "_elems;";
00810       nl(Out);
00811       for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
00812         Constant *Elt = CDS->getElementAsConstant(i);
00813         printConstant(Elt);
00814         Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
00815         nl(Out);
00816       }
00817       Out << "Constant* " << constName;
00818       
00819       if (isa<ArrayType>(CDS->getType()))
00820         Out << " = ConstantArray::get(";
00821       else
00822         Out << " = ConstantVector::get(";
00823       Out << typeName << ", " << constName << "_elems);";
00824     }
00825   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
00826     if (CE->getOpcode() == Instruction::GetElementPtr) {
00827       Out << "std::vector<Constant*> " << constName << "_indices;";
00828       nl(Out);
00829       printConstant(CE->getOperand(0));
00830       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
00831         printConstant(CE->getOperand(i));
00832         Out << constName << "_indices.push_back("
00833             << getCppName(CE->getOperand(i)) << ");";
00834         nl(Out);
00835       }
00836       Out << "Constant* " << constName
00837           << " = ConstantExpr::getGetElementPtr("
00838           << getCppName(CE->getOperand(0)) << ", "
00839           << constName << "_indices);";
00840     } else if (CE->isCast()) {
00841       printConstant(CE->getOperand(0));
00842       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
00843       switch (CE->getOpcode()) {
00844       default: llvm_unreachable("Invalid cast opcode");
00845       case Instruction::Trunc: Out << "Instruction::Trunc"; break;
00846       case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
00847       case Instruction::SExt:  Out << "Instruction::SExt"; break;
00848       case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
00849       case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
00850       case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
00851       case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
00852       case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
00853       case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
00854       case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
00855       case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
00856       case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
00857       }
00858       Out << ", " << getCppName(CE->getOperand(0)) << ", "
00859           << getCppName(CE->getType()) << ");";
00860     } else {
00861       unsigned N = CE->getNumOperands();
00862       for (unsigned i = 0; i < N; ++i ) {
00863         printConstant(CE->getOperand(i));
00864       }
00865       Out << "Constant* " << constName << " = ConstantExpr::";
00866       switch (CE->getOpcode()) {
00867       case Instruction::Add:    Out << "getAdd(";  break;
00868       case Instruction::FAdd:   Out << "getFAdd(";  break;
00869       case Instruction::Sub:    Out << "getSub("; break;
00870       case Instruction::FSub:   Out << "getFSub("; break;
00871       case Instruction::Mul:    Out << "getMul("; break;
00872       case Instruction::FMul:   Out << "getFMul("; break;
00873       case Instruction::UDiv:   Out << "getUDiv("; break;
00874       case Instruction::SDiv:   Out << "getSDiv("; break;
00875       case Instruction::FDiv:   Out << "getFDiv("; break;
00876       case Instruction::URem:   Out << "getURem("; break;
00877       case Instruction::SRem:   Out << "getSRem("; break;
00878       case Instruction::FRem:   Out << "getFRem("; break;
00879       case Instruction::And:    Out << "getAnd("; break;
00880       case Instruction::Or:     Out << "getOr("; break;
00881       case Instruction::Xor:    Out << "getXor("; break;
00882       case Instruction::ICmp:
00883         Out << "getICmp(ICmpInst::ICMP_";
00884         switch (CE->getPredicate()) {
00885         case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
00886         case ICmpInst::ICMP_NE:  Out << "NE"; break;
00887         case ICmpInst::ICMP_SLT: Out << "SLT"; break;
00888         case ICmpInst::ICMP_ULT: Out << "ULT"; break;
00889         case ICmpInst::ICMP_SGT: Out << "SGT"; break;
00890         case ICmpInst::ICMP_UGT: Out << "UGT"; break;
00891         case ICmpInst::ICMP_SLE: Out << "SLE"; break;
00892         case ICmpInst::ICMP_ULE: Out << "ULE"; break;
00893         case ICmpInst::ICMP_SGE: Out << "SGE"; break;
00894         case ICmpInst::ICMP_UGE: Out << "UGE"; break;
00895         default: error("Invalid ICmp Predicate");
00896         }
00897         break;
00898       case Instruction::FCmp:
00899         Out << "getFCmp(FCmpInst::FCMP_";
00900         switch (CE->getPredicate()) {
00901         case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
00902         case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
00903         case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
00904         case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
00905         case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
00906         case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
00907         case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
00908         case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
00909         case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
00910         case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
00911         case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
00912         case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
00913         case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
00914         case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
00915         case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
00916         case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
00917         default: error("Invalid FCmp Predicate");
00918         }
00919         break;
00920       case Instruction::Shl:     Out << "getShl("; break;
00921       case Instruction::LShr:    Out << "getLShr("; break;
00922       case Instruction::AShr:    Out << "getAShr("; break;
00923       case Instruction::Select:  Out << "getSelect("; break;
00924       case Instruction::ExtractElement: Out << "getExtractElement("; break;
00925       case Instruction::InsertElement:  Out << "getInsertElement("; break;
00926       case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
00927       default:
00928         error("Invalid constant expression");
00929         break;
00930       }
00931       Out << getCppName(CE->getOperand(0));
00932       for (unsigned i = 1; i < CE->getNumOperands(); ++i)
00933         Out << ", " << getCppName(CE->getOperand(i));
00934       Out << ");";
00935     }
00936   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
00937     Out << "Constant* " << constName << " = ";
00938     Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
00939   } else {
00940     error("Bad Constant");
00941     Out << "Constant* " << constName << " = 0; ";
00942   }
00943   nl(Out);
00944 }
00945 
00946 void CppWriter::printConstants(const Module* M) {
00947   // Traverse all the global variables looking for constant initializers
00948   for (Module::const_global_iterator I = TheModule->global_begin(),
00949          E = TheModule->global_end(); I != E; ++I)
00950     if (I->hasInitializer())
00951       printConstant(I->getInitializer());
00952 
00953   // Traverse the LLVM functions looking for constants
00954   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00955        FI != FE; ++FI) {
00956     // Add all of the basic blocks and instructions
00957     for (Function::const_iterator BB = FI->begin(),
00958            E = FI->end(); BB != E; ++BB) {
00959       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00960            ++I) {
00961         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
00962           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
00963             printConstant(C);
00964           }
00965         }
00966       }
00967     }
00968   }
00969 }
00970 
00971 void CppWriter::printVariableUses(const GlobalVariable *GV) {
00972   nl(Out) << "// Type Definitions";
00973   nl(Out);
00974   printType(GV->getType());
00975   if (GV->hasInitializer()) {
00976     const Constant *Init = GV->getInitializer();
00977     printType(Init->getType());
00978     if (const Function *F = dyn_cast<Function>(Init)) {
00979       nl(Out)<< "/ Function Declarations"; nl(Out);
00980       printFunctionHead(F);
00981     } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
00982       nl(Out) << "// Global Variable Declarations"; nl(Out);
00983       printVariableHead(gv);
00984       
00985       nl(Out) << "// Global Variable Definitions"; nl(Out);
00986       printVariableBody(gv);
00987     } else  {
00988       nl(Out) << "// Constant Definitions"; nl(Out);
00989       printConstant(Init);
00990     }
00991   }
00992 }
00993 
00994 void CppWriter::printVariableHead(const GlobalVariable *GV) {
00995   nl(Out) << "GlobalVariable* " << getCppName(GV);
00996   if (is_inline) {
00997     Out << " = mod->getGlobalVariable(mod->getContext(), ";
00998     printEscapedString(GV->getName());
00999     Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
01000     nl(Out) << "if (!" << getCppName(GV) << ") {";
01001     in(); nl(Out) << getCppName(GV);
01002   }
01003   Out << " = new GlobalVariable(/*Module=*/*mod, ";
01004   nl(Out) << "/*Type=*/";
01005   printCppName(GV->getType()->getElementType());
01006   Out << ",";
01007   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
01008   Out << ",";
01009   nl(Out) << "/*Linkage=*/";
01010   printLinkageType(GV->getLinkage());
01011   Out << ",";
01012   nl(Out) << "/*Initializer=*/0, ";
01013   if (GV->hasInitializer()) {
01014     Out << "// has initializer, specified below";
01015   }
01016   nl(Out) << "/*Name=*/\"";
01017   printEscapedString(GV->getName());
01018   Out << "\");";
01019   nl(Out);
01020 
01021   if (GV->hasSection()) {
01022     printCppName(GV);
01023     Out << "->setSection(\"";
01024     printEscapedString(GV->getSection());
01025     Out << "\");";
01026     nl(Out);
01027   }
01028   if (GV->getAlignment()) {
01029     printCppName(GV);
01030     Out << "->setAlignment(" << GV->getAlignment() << ");";
01031     nl(Out);
01032   }
01033   if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
01034     printCppName(GV);
01035     Out << "->setVisibility(";
01036     printVisibilityType(GV->getVisibility());
01037     Out << ");";
01038     nl(Out);
01039   }
01040   if (GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01041     printCppName(GV);
01042     Out << "->setDLLStorageClass(";
01043     printDLLStorageClassType(GV->getDLLStorageClass());
01044     Out << ");";
01045     nl(Out);
01046   }
01047   if (GV->isThreadLocal()) {
01048     printCppName(GV);
01049     Out << "->setThreadLocalMode(";
01050     printThreadLocalMode(GV->getThreadLocalMode());
01051     Out << ");";
01052     nl(Out);
01053   }
01054   if (is_inline) {
01055     out(); Out << "}"; nl(Out);
01056   }
01057 }
01058 
01059 void CppWriter::printVariableBody(const GlobalVariable *GV) {
01060   if (GV->hasInitializer()) {
01061     printCppName(GV);
01062     Out << "->setInitializer(";
01063     Out << getCppName(GV->getInitializer()) << ");";
01064     nl(Out);
01065   }
01066 }
01067 
01068 std::string CppWriter::getOpName(const Value* V) {
01069   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
01070     return getCppName(V);
01071 
01072   // See if its alread in the map of forward references, if so just return the
01073   // name we already set up for it
01074   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
01075   if (I != ForwardRefs.end())
01076     return I->second;
01077 
01078   // This is a new forward reference. Generate a unique name for it
01079   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
01080 
01081   // Yes, this is a hack. An Argument is the smallest instantiable value that
01082   // we can make as a placeholder for the real value. We'll replace these
01083   // Argument instances later.
01084   Out << "Argument* " << result << " = new Argument("
01085       << getCppName(V->getType()) << ");";
01086   nl(Out);
01087   ForwardRefs[V] = result;
01088   return result;
01089 }
01090 
01091 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
01092   switch (Ordering) {
01093     case NotAtomic: return "NotAtomic";
01094     case Unordered: return "Unordered";
01095     case Monotonic: return "Monotonic";
01096     case Acquire: return "Acquire";
01097     case Release: return "Release";
01098     case AcquireRelease: return "AcquireRelease";
01099     case SequentiallyConsistent: return "SequentiallyConsistent";
01100   }
01101   llvm_unreachable("Unknown ordering");
01102 }
01103 
01104 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
01105   switch (SynchScope) {
01106     case SingleThread: return "SingleThread";
01107     case CrossThread: return "CrossThread";
01108   }
01109   llvm_unreachable("Unknown synch scope");
01110 }
01111 
01112 // printInstruction - This member is called for each Instruction in a function.
01113 void CppWriter::printInstruction(const Instruction *I,
01114                                  const std::string& bbname) {
01115   std::string iName(getCppName(I));
01116 
01117   // Before we emit this instruction, we need to take care of generating any
01118   // forward references. So, we get the names of all the operands in advance
01119   const unsigned Ops(I->getNumOperands());
01120   std::string* opNames = new std::string[Ops];
01121   for (unsigned i = 0; i < Ops; i++)
01122     opNames[i] = getOpName(I->getOperand(i));
01123 
01124   switch (I->getOpcode()) {
01125   default:
01126     error("Invalid instruction");
01127     break;
01128 
01129   case Instruction::Ret: {
01130     const ReturnInst* ret =  cast<ReturnInst>(I);
01131     Out << "ReturnInst::Create(mod->getContext(), "
01132         << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
01133     break;
01134   }
01135   case Instruction::Br: {
01136     const BranchInst* br = cast<BranchInst>(I);
01137     Out << "BranchInst::Create(" ;
01138     if (br->getNumOperands() == 3) {
01139       Out << opNames[2] << ", "
01140           << opNames[1] << ", "
01141           << opNames[0] << ", ";
01142 
01143     } else if (br->getNumOperands() == 1) {
01144       Out << opNames[0] << ", ";
01145     } else {
01146       error("Branch with 2 operands?");
01147     }
01148     Out << bbname << ");";
01149     break;
01150   }
01151   case Instruction::Switch: {
01152     const SwitchInst *SI = cast<SwitchInst>(I);
01153     Out << "SwitchInst* " << iName << " = SwitchInst::Create("
01154         << getOpName(SI->getCondition()) << ", "
01155         << getOpName(SI->getDefaultDest()) << ", "
01156         << SI->getNumCases() << ", " << bbname << ");";
01157     nl(Out);
01158     for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
01159          i != e; ++i) {
01160       const ConstantInt* CaseVal = i.getCaseValue();
01161       const BasicBlock *BB = i.getCaseSuccessor();
01162       Out << iName << "->addCase("
01163           << getOpName(CaseVal) << ", "
01164           << getOpName(BB) << ");";
01165       nl(Out);
01166     }
01167     break;
01168   }
01169   case Instruction::IndirectBr: {
01170     const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
01171     Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
01172         << opNames[0] << ", " << IBI->getNumDestinations() << ");";
01173     nl(Out);
01174     for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
01175       Out << iName << "->addDestination(" << opNames[i] << ");";
01176       nl(Out);
01177     }
01178     break;
01179   }
01180   case Instruction::Resume: {
01181     Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
01182     break;
01183   }
01184   case Instruction::Invoke: {
01185     const InvokeInst* inv = cast<InvokeInst>(I);
01186     Out << "std::vector<Value*> " << iName << "_params;";
01187     nl(Out);
01188     for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
01189       Out << iName << "_params.push_back("
01190           << getOpName(inv->getArgOperand(i)) << ");";
01191       nl(Out);
01192     }
01193     // FIXME: This shouldn't use magic numbers -3, -2, and -1.
01194     Out << "InvokeInst *" << iName << " = InvokeInst::Create("
01195         << getOpName(inv->getCalledValue()) << ", "
01196         << getOpName(inv->getNormalDest()) << ", "
01197         << getOpName(inv->getUnwindDest()) << ", "
01198         << iName << "_params, \"";
01199     printEscapedString(inv->getName());
01200     Out << "\", " << bbname << ");";
01201     nl(Out) << iName << "->setCallingConv(";
01202     printCallingConv(inv->getCallingConv());
01203     Out << ");";
01204     printAttributes(inv->getAttributes(), iName);
01205     Out << iName << "->setAttributes(" << iName << "_PAL);";
01206     nl(Out);
01207     break;
01208   }
01209   case Instruction::Unreachable: {
01210     Out << "new UnreachableInst("
01211         << "mod->getContext(), "
01212         << bbname << ");";
01213     break;
01214   }
01215   case Instruction::Add:
01216   case Instruction::FAdd:
01217   case Instruction::Sub:
01218   case Instruction::FSub:
01219   case Instruction::Mul:
01220   case Instruction::FMul:
01221   case Instruction::UDiv:
01222   case Instruction::SDiv:
01223   case Instruction::FDiv:
01224   case Instruction::URem:
01225   case Instruction::SRem:
01226   case Instruction::FRem:
01227   case Instruction::And:
01228   case Instruction::Or:
01229   case Instruction::Xor:
01230   case Instruction::Shl:
01231   case Instruction::LShr:
01232   case Instruction::AShr:{
01233     Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
01234     switch (I->getOpcode()) {
01235     case Instruction::Add: Out << "Instruction::Add"; break;
01236     case Instruction::FAdd: Out << "Instruction::FAdd"; break;
01237     case Instruction::Sub: Out << "Instruction::Sub"; break;
01238     case Instruction::FSub: Out << "Instruction::FSub"; break;
01239     case Instruction::Mul: Out << "Instruction::Mul"; break;
01240     case Instruction::FMul: Out << "Instruction::FMul"; break;
01241     case Instruction::UDiv:Out << "Instruction::UDiv"; break;
01242     case Instruction::SDiv:Out << "Instruction::SDiv"; break;
01243     case Instruction::FDiv:Out << "Instruction::FDiv"; break;
01244     case Instruction::URem:Out << "Instruction::URem"; break;
01245     case Instruction::SRem:Out << "Instruction::SRem"; break;
01246     case Instruction::FRem:Out << "Instruction::FRem"; break;
01247     case Instruction::And: Out << "Instruction::And"; break;
01248     case Instruction::Or:  Out << "Instruction::Or";  break;
01249     case Instruction::Xor: Out << "Instruction::Xor"; break;
01250     case Instruction::Shl: Out << "Instruction::Shl"; break;
01251     case Instruction::LShr:Out << "Instruction::LShr"; break;
01252     case Instruction::AShr:Out << "Instruction::AShr"; break;
01253     default: Out << "Instruction::BadOpCode"; break;
01254     }
01255     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01256     printEscapedString(I->getName());
01257     Out << "\", " << bbname << ");";
01258     break;
01259   }
01260   case Instruction::FCmp: {
01261     Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
01262     switch (cast<FCmpInst>(I)->getPredicate()) {
01263     case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
01264     case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
01265     case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
01266     case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
01267     case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
01268     case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
01269     case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
01270     case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
01271     case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
01272     case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
01273     case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
01274     case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
01275     case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
01276     case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
01277     case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
01278     case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
01279     default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
01280     }
01281     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01282     printEscapedString(I->getName());
01283     Out << "\");";
01284     break;
01285   }
01286   case Instruction::ICmp: {
01287     Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
01288     switch (cast<ICmpInst>(I)->getPredicate()) {
01289     case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
01290     case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
01291     case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
01292     case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
01293     case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
01294     case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
01295     case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
01296     case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
01297     case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
01298     case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
01299     default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
01300     }
01301     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01302     printEscapedString(I->getName());
01303     Out << "\");";
01304     break;
01305   }
01306   case Instruction::Alloca: {
01307     const AllocaInst* allocaI = cast<AllocaInst>(I);
01308     Out << "AllocaInst* " << iName << " = new AllocaInst("
01309         << getCppName(allocaI->getAllocatedType()) << ", ";
01310     if (allocaI->isArrayAllocation())
01311       Out << opNames[0] << ", ";
01312     Out << "\"";
01313     printEscapedString(allocaI->getName());
01314     Out << "\", " << bbname << ");";
01315     if (allocaI->getAlignment())
01316       nl(Out) << iName << "->setAlignment("
01317           << allocaI->getAlignment() << ");";
01318     break;
01319   }
01320   case Instruction::Load: {
01321     const LoadInst* load = cast<LoadInst>(I);
01322     Out << "LoadInst* " << iName << " = new LoadInst("
01323         << opNames[0] << ", \"";
01324     printEscapedString(load->getName());
01325     Out << "\", " << (load->isVolatile() ? "true" : "false" )
01326         << ", " << bbname << ");";
01327     if (load->getAlignment())
01328       nl(Out) << iName << "->setAlignment("
01329               << load->getAlignment() << ");";
01330     if (load->isAtomic()) {
01331       StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
01332       StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
01333       nl(Out) << iName << "->setAtomic("
01334               << Ordering << ", " << CrossThread << ");";
01335     }
01336     break;
01337   }
01338   case Instruction::Store: {
01339     const StoreInst* store = cast<StoreInst>(I);
01340     Out << "StoreInst* " << iName << " = new StoreInst("
01341         << opNames[0] << ", "
01342         << opNames[1] << ", "
01343         << (store->isVolatile() ? "true" : "false")
01344         << ", " << bbname << ");";
01345     if (store->getAlignment())
01346       nl(Out) << iName << "->setAlignment("
01347               << store->getAlignment() << ");";
01348     if (store->isAtomic()) {
01349       StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
01350       StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
01351       nl(Out) << iName << "->setAtomic("
01352               << Ordering << ", " << CrossThread << ");";
01353     }
01354     break;
01355   }
01356   case Instruction::GetElementPtr: {
01357     const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
01358     if (gep->getNumOperands() <= 2) {
01359       Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
01360           << opNames[0];
01361       if (gep->getNumOperands() == 2)
01362         Out << ", " << opNames[1];
01363     } else {
01364       Out << "std::vector<Value*> " << iName << "_indices;";
01365       nl(Out);
01366       for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
01367         Out << iName << "_indices.push_back("
01368             << opNames[i] << ");";
01369         nl(Out);
01370       }
01371       Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
01372           << opNames[0] << ", " << iName << "_indices";
01373     }
01374     Out << ", \"";
01375     printEscapedString(gep->getName());
01376     Out << "\", " << bbname << ");";
01377     break;
01378   }
01379   case Instruction::PHI: {
01380     const PHINode* phi = cast<PHINode>(I);
01381 
01382     Out << "PHINode* " << iName << " = PHINode::Create("
01383         << getCppName(phi->getType()) << ", "
01384         << phi->getNumIncomingValues() << ", \"";
01385     printEscapedString(phi->getName());
01386     Out << "\", " << bbname << ");";
01387     nl(Out);
01388     for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
01389       Out << iName << "->addIncoming("
01390           << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
01391           << getOpName(phi->getIncomingBlock(i)) << ");";
01392       nl(Out);
01393     }
01394     break;
01395   }
01396   case Instruction::Trunc:
01397   case Instruction::ZExt:
01398   case Instruction::SExt:
01399   case Instruction::FPTrunc:
01400   case Instruction::FPExt:
01401   case Instruction::FPToUI:
01402   case Instruction::FPToSI:
01403   case Instruction::UIToFP:
01404   case Instruction::SIToFP:
01405   case Instruction::PtrToInt:
01406   case Instruction::IntToPtr:
01407   case Instruction::BitCast: {
01408     const CastInst* cst = cast<CastInst>(I);
01409     Out << "CastInst* " << iName << " = new ";
01410     switch (I->getOpcode()) {
01411     case Instruction::Trunc:    Out << "TruncInst"; break;
01412     case Instruction::ZExt:     Out << "ZExtInst"; break;
01413     case Instruction::SExt:     Out << "SExtInst"; break;
01414     case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
01415     case Instruction::FPExt:    Out << "FPExtInst"; break;
01416     case Instruction::FPToUI:   Out << "FPToUIInst"; break;
01417     case Instruction::FPToSI:   Out << "FPToSIInst"; break;
01418     case Instruction::UIToFP:   Out << "UIToFPInst"; break;
01419     case Instruction::SIToFP:   Out << "SIToFPInst"; break;
01420     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
01421     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
01422     case Instruction::BitCast:  Out << "BitCastInst"; break;
01423     default: llvm_unreachable("Unreachable");
01424     }
01425     Out << "(" << opNames[0] << ", "
01426         << getCppName(cst->getType()) << ", \"";
01427     printEscapedString(cst->getName());
01428     Out << "\", " << bbname << ");";
01429     break;
01430   }
01431   case Instruction::Call: {
01432     const CallInst* call = cast<CallInst>(I);
01433     if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
01434       Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
01435           << getCppName(ila->getFunctionType()) << ", \""
01436           << ila->getAsmString() << "\", \""
01437           << ila->getConstraintString() << "\","
01438           << (ila->hasSideEffects() ? "true" : "false") << ");";
01439       nl(Out);
01440     }
01441     if (call->getNumArgOperands() > 1) {
01442       Out << "std::vector<Value*> " << iName << "_params;";
01443       nl(Out);
01444       for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
01445         Out << iName << "_params.push_back(" << opNames[i] << ");";
01446         nl(Out);
01447       }
01448       Out << "CallInst* " << iName << " = CallInst::Create("
01449           << opNames[call->getNumArgOperands()] << ", "
01450           << iName << "_params, \"";
01451     } else if (call->getNumArgOperands() == 1) {
01452       Out << "CallInst* " << iName << " = CallInst::Create("
01453           << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
01454     } else {
01455       Out << "CallInst* " << iName << " = CallInst::Create("
01456           << opNames[call->getNumArgOperands()] << ", \"";
01457     }
01458     printEscapedString(call->getName());
01459     Out << "\", " << bbname << ");";
01460     nl(Out) << iName << "->setCallingConv(";
01461     printCallingConv(call->getCallingConv());
01462     Out << ");";
01463     nl(Out) << iName << "->setTailCall("
01464         << (call->isTailCall() ? "true" : "false");
01465     Out << ");";
01466     nl(Out);
01467     printAttributes(call->getAttributes(), iName);
01468     Out << iName << "->setAttributes(" << iName << "_PAL);";
01469     nl(Out);
01470     break;
01471   }
01472   case Instruction::Select: {
01473     const SelectInst* sel = cast<SelectInst>(I);
01474     Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
01475     Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01476     printEscapedString(sel->getName());
01477     Out << "\", " << bbname << ");";
01478     break;
01479   }
01480   case Instruction::UserOp1:
01481     /// FALL THROUGH
01482   case Instruction::UserOp2: {
01483     /// FIXME: What should be done here?
01484     break;
01485   }
01486   case Instruction::VAArg: {
01487     const VAArgInst* va = cast<VAArgInst>(I);
01488     Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
01489         << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
01490     printEscapedString(va->getName());
01491     Out << "\", " << bbname << ");";
01492     break;
01493   }
01494   case Instruction::ExtractElement: {
01495     const ExtractElementInst* eei = cast<ExtractElementInst>(I);
01496     Out << "ExtractElementInst* " << getCppName(eei)
01497         << " = new ExtractElementInst(" << opNames[0]
01498         << ", " << opNames[1] << ", \"";
01499     printEscapedString(eei->getName());
01500     Out << "\", " << bbname << ");";
01501     break;
01502   }
01503   case Instruction::InsertElement: {
01504     const InsertElementInst* iei = cast<InsertElementInst>(I);
01505     Out << "InsertElementInst* " << getCppName(iei)
01506         << " = InsertElementInst::Create(" << opNames[0]
01507         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01508     printEscapedString(iei->getName());
01509     Out << "\", " << bbname << ");";
01510     break;
01511   }
01512   case Instruction::ShuffleVector: {
01513     const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
01514     Out << "ShuffleVectorInst* " << getCppName(svi)
01515         << " = new ShuffleVectorInst(" << opNames[0]
01516         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01517     printEscapedString(svi->getName());
01518     Out << "\", " << bbname << ");";
01519     break;
01520   }
01521   case Instruction::ExtractValue: {
01522     const ExtractValueInst *evi = cast<ExtractValueInst>(I);
01523     Out << "std::vector<unsigned> " << iName << "_indices;";
01524     nl(Out);
01525     for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
01526       Out << iName << "_indices.push_back("
01527           << evi->idx_begin()[i] << ");";
01528       nl(Out);
01529     }
01530     Out << "ExtractValueInst* " << getCppName(evi)
01531         << " = ExtractValueInst::Create(" << opNames[0]
01532         << ", "
01533         << iName << "_indices, \"";
01534     printEscapedString(evi->getName());
01535     Out << "\", " << bbname << ");";
01536     break;
01537   }
01538   case Instruction::InsertValue: {
01539     const InsertValueInst *ivi = cast<InsertValueInst>(I);
01540     Out << "std::vector<unsigned> " << iName << "_indices;";
01541     nl(Out);
01542     for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
01543       Out << iName << "_indices.push_back("
01544           << ivi->idx_begin()[i] << ");";
01545       nl(Out);
01546     }
01547     Out << "InsertValueInst* " << getCppName(ivi)
01548         << " = InsertValueInst::Create(" << opNames[0]
01549         << ", " << opNames[1] << ", "
01550         << iName << "_indices, \"";
01551     printEscapedString(ivi->getName());
01552     Out << "\", " << bbname << ");";
01553     break;
01554   }
01555   case Instruction::Fence: {
01556     const FenceInst *fi = cast<FenceInst>(I);
01557     StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
01558     StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
01559     Out << "FenceInst* " << iName
01560         << " = new FenceInst(mod->getContext(), "
01561         << Ordering << ", " << CrossThread << ", " << bbname
01562         << ");";
01563     break;
01564   }
01565   case Instruction::AtomicCmpXchg: {
01566     const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
01567     StringRef SuccessOrdering =
01568         ConvertAtomicOrdering(cxi->getSuccessOrdering());
01569     StringRef FailureOrdering =
01570         ConvertAtomicOrdering(cxi->getFailureOrdering());
01571     StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
01572     Out << "AtomicCmpXchgInst* " << iName
01573         << " = new AtomicCmpXchgInst("
01574         << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
01575         << SuccessOrdering << ", " << FailureOrdering << ", "
01576         << CrossThread << ", " << bbname
01577         << ");";
01578     nl(Out) << iName << "->setName(\"";
01579     printEscapedString(cxi->getName());
01580     Out << "\");";
01581     nl(Out) << iName << "->setVolatile("
01582             << (cxi->isVolatile() ? "true" : "false") << ");";
01583     nl(Out) << iName << "->setWeak("
01584             << (cxi->isWeak() ? "true" : "false") << ");";
01585     break;
01586   }
01587   case Instruction::AtomicRMW: {
01588     const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
01589     StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
01590     StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
01591     StringRef Operation;
01592     switch (rmwi->getOperation()) {
01593       case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
01594       case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
01595       case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
01596       case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
01597       case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
01598       case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
01599       case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
01600       case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
01601       case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
01602       case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
01603       case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
01604       case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
01605     }
01606     Out << "AtomicRMWInst* " << iName
01607         << " = new AtomicRMWInst("
01608         << Operation << ", "
01609         << opNames[0] << ", " << opNames[1] << ", "
01610         << Ordering << ", " << CrossThread << ", " << bbname
01611         << ");";
01612     nl(Out) << iName << "->setName(\"";
01613     printEscapedString(rmwi->getName());
01614     Out << "\");";
01615     nl(Out) << iName << "->setVolatile("
01616             << (rmwi->isVolatile() ? "true" : "false") << ");";
01617     break;
01618   }
01619   case Instruction::LandingPad: {
01620     const LandingPadInst *lpi = cast<LandingPadInst>(I);
01621     Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
01622     printCppName(lpi->getType());
01623     Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
01624     printEscapedString(lpi->getName());
01625     Out << "\", " << bbname << ");";
01626     nl(Out) << iName << "->setCleanup("
01627             << (lpi->isCleanup() ? "true" : "false")
01628             << ");";
01629     for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
01630       nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
01631     break;
01632   }
01633   }
01634   DefinedValues.insert(I);
01635   nl(Out);
01636   delete [] opNames;
01637 }
01638 
01639 // Print out the types, constants and declarations needed by one function
01640 void CppWriter::printFunctionUses(const Function* F) {
01641   nl(Out) << "// Type Definitions"; nl(Out);
01642   if (!is_inline) {
01643     // Print the function's return type
01644     printType(F->getReturnType());
01645 
01646     // Print the function's function type
01647     printType(F->getFunctionType());
01648 
01649     // Print the types of each of the function's arguments
01650     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01651          AI != AE; ++AI) {
01652       printType(AI->getType());
01653     }
01654   }
01655 
01656   // Print type definitions for every type referenced by an instruction and
01657   // make a note of any global values or constants that are referenced
01658   SmallPtrSet<GlobalValue*,64> gvs;
01659   SmallPtrSet<Constant*,64> consts;
01660   for (Function::const_iterator BB = F->begin(), BE = F->end();
01661        BB != BE; ++BB){
01662     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01663          I != E; ++I) {
01664       // Print the type of the instruction itself
01665       printType(I->getType());
01666 
01667       // Print the type of each of the instruction's operands
01668       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
01669         Value* operand = I->getOperand(i);
01670         printType(operand->getType());
01671 
01672         // If the operand references a GVal or Constant, make a note of it
01673         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01674           gvs.insert(GV);
01675           if (GenerationType != GenFunction)
01676             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01677               if (GVar->hasInitializer())
01678                 consts.insert(GVar->getInitializer());
01679         } else if (Constant* C = dyn_cast<Constant>(operand)) {
01680           consts.insert(C);
01681           for (unsigned j = 0; j < C->getNumOperands(); ++j) {
01682             // If the operand references a GVal or Constant, make a note of it
01683             Value* operand = C->getOperand(j);
01684             printType(operand->getType());
01685             if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01686               gvs.insert(GV);
01687               if (GenerationType != GenFunction)
01688                 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01689                   if (GVar->hasInitializer())
01690                     consts.insert(GVar->getInitializer());
01691             }
01692           }
01693         }
01694       }
01695     }
01696   }
01697 
01698   // Print the function declarations for any functions encountered
01699   nl(Out) << "// Function Declarations"; nl(Out);
01700   for (auto *GV : gvs) {
01701     if (Function *Fun = dyn_cast<Function>(GV)) {
01702       if (!is_inline || Fun != F)
01703         printFunctionHead(Fun);
01704     }
01705   }
01706 
01707   // Print the global variable declarations for any variables encountered
01708   nl(Out) << "// Global Variable Declarations"; nl(Out);
01709   for (auto *GV : gvs) {
01710     if (GlobalVariable *F = dyn_cast<GlobalVariable>(GV))
01711       printVariableHead(F);
01712   }
01713 
01714   // Print the constants found
01715   nl(Out) << "// Constant Definitions"; nl(Out);
01716   for (const auto *C : consts) {
01717     printConstant(C);
01718   }
01719 
01720   // Process the global variables definitions now that all the constants have
01721   // been emitted. These definitions just couple the gvars with their constant
01722   // initializers.
01723   if (GenerationType != GenFunction) {
01724     nl(Out) << "// Global Variable Definitions"; nl(Out);
01725     for (auto *GV : gvs) {
01726       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(GV))
01727         printVariableBody(Var);
01728     }
01729   }
01730 }
01731 
01732 void CppWriter::printFunctionHead(const Function* F) {
01733   nl(Out) << "Function* " << getCppName(F);
01734   Out << " = mod->getFunction(\"";
01735   printEscapedString(F->getName());
01736   Out << "\");";
01737   nl(Out) << "if (!" << getCppName(F) << ") {";
01738   nl(Out) << getCppName(F);
01739 
01740   Out<< " = Function::Create(";
01741   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
01742   nl(Out) << "/*Linkage=*/";
01743   printLinkageType(F->getLinkage());
01744   Out << ",";
01745   nl(Out) << "/*Name=*/\"";
01746   printEscapedString(F->getName());
01747   Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
01748   nl(Out,-1);
01749   printCppName(F);
01750   Out << "->setCallingConv(";
01751   printCallingConv(F->getCallingConv());
01752   Out << ");";
01753   nl(Out);
01754   if (F->hasSection()) {
01755     printCppName(F);
01756     Out << "->setSection(\"" << F->getSection() << "\");";
01757     nl(Out);
01758   }
01759   if (F->getAlignment()) {
01760     printCppName(F);
01761     Out << "->setAlignment(" << F->getAlignment() << ");";
01762     nl(Out);
01763   }
01764   if (F->getVisibility() != GlobalValue::DefaultVisibility) {
01765     printCppName(F);
01766     Out << "->setVisibility(";
01767     printVisibilityType(F->getVisibility());
01768     Out << ");";
01769     nl(Out);
01770   }
01771   if (F->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01772     printCppName(F);
01773     Out << "->setDLLStorageClass(";
01774     printDLLStorageClassType(F->getDLLStorageClass());
01775     Out << ");";
01776     nl(Out);
01777   }
01778   if (F->hasGC()) {
01779     printCppName(F);
01780     Out << "->setGC(\"" << F->getGC() << "\");";
01781     nl(Out);
01782   }
01783   Out << "}";
01784   nl(Out);
01785   printAttributes(F->getAttributes(), getCppName(F));
01786   printCppName(F);
01787   Out << "->setAttributes(" << getCppName(F) << "_PAL);";
01788   nl(Out);
01789 }
01790 
01791 void CppWriter::printFunctionBody(const Function *F) {
01792   if (F->isDeclaration())
01793     return; // external functions have no bodies.
01794 
01795   // Clear the DefinedValues and ForwardRefs maps because we can't have
01796   // cross-function forward refs
01797   ForwardRefs.clear();
01798   DefinedValues.clear();
01799 
01800   // Create all the argument values
01801   if (!is_inline) {
01802     if (!F->arg_empty()) {
01803       Out << "Function::arg_iterator args = " << getCppName(F)
01804           << "->arg_begin();";
01805       nl(Out);
01806     }
01807     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01808          AI != AE; ++AI) {
01809       Out << "Value* " << getCppName(AI) << " = args++;";
01810       nl(Out);
01811       if (AI->hasName()) {
01812         Out << getCppName(AI) << "->setName(\"";
01813         printEscapedString(AI->getName());
01814         Out << "\");";
01815         nl(Out);
01816       }
01817     }
01818   }
01819 
01820   // Create all the basic blocks
01821   nl(Out);
01822   for (Function::const_iterator BI = F->begin(), BE = F->end();
01823        BI != BE; ++BI) {
01824     std::string bbname(getCppName(BI));
01825     Out << "BasicBlock* " << bbname <<
01826            " = BasicBlock::Create(mod->getContext(), \"";
01827     if (BI->hasName())
01828       printEscapedString(BI->getName());
01829     Out << "\"," << getCppName(BI->getParent()) << ",0);";
01830     nl(Out);
01831   }
01832 
01833   // Output all of its basic blocks... for the function
01834   for (Function::const_iterator BI = F->begin(), BE = F->end();
01835        BI != BE; ++BI) {
01836     std::string bbname(getCppName(BI));
01837     nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
01838     nl(Out);
01839 
01840     // Output all of the instructions in the basic block...
01841     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
01842          I != E; ++I) {
01843       printInstruction(I,bbname);
01844     }
01845   }
01846 
01847   // Loop over the ForwardRefs and resolve them now that all instructions
01848   // are generated.
01849   if (!ForwardRefs.empty()) {
01850     nl(Out) << "// Resolve Forward References";
01851     nl(Out);
01852   }
01853 
01854   while (!ForwardRefs.empty()) {
01855     ForwardRefMap::iterator I = ForwardRefs.begin();
01856     Out << I->second << "->replaceAllUsesWith("
01857         << getCppName(I->first) << "); delete " << I->second << ";";
01858     nl(Out);
01859     ForwardRefs.erase(I);
01860   }
01861 }
01862 
01863 void CppWriter::printInline(const std::string& fname,
01864                             const std::string& func) {
01865   const Function* F = TheModule->getFunction(func);
01866   if (!F) {
01867     error(std::string("Function '") + func + "' not found in input module");
01868     return;
01869   }
01870   if (F->isDeclaration()) {
01871     error(std::string("Function '") + func + "' is external!");
01872     return;
01873   }
01874   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
01875           << getCppName(F);
01876   unsigned arg_count = 1;
01877   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01878        AI != AE; ++AI) {
01879     Out << ", Value* arg_" << arg_count++;
01880   }
01881   Out << ") {";
01882   nl(Out);
01883   is_inline = true;
01884   printFunctionUses(F);
01885   printFunctionBody(F);
01886   is_inline = false;
01887   Out << "return " << getCppName(F->begin()) << ";";
01888   nl(Out) << "}";
01889   nl(Out);
01890 }
01891 
01892 void CppWriter::printModuleBody() {
01893   // Print out all the type definitions
01894   nl(Out) << "// Type Definitions"; nl(Out);
01895   printTypes(TheModule);
01896 
01897   // Functions can call each other and global variables can reference them so
01898   // define all the functions first before emitting their function bodies.
01899   nl(Out) << "// Function Declarations"; nl(Out);
01900   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
01901        I != E; ++I)
01902     printFunctionHead(I);
01903 
01904   // Process the global variables declarations. We can't initialze them until
01905   // after the constants are printed so just print a header for each global
01906   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
01907   for (Module::const_global_iterator I = TheModule->global_begin(),
01908          E = TheModule->global_end(); I != E; ++I) {
01909     printVariableHead(I);
01910   }
01911 
01912   // Print out all the constants definitions. Constants don't recurse except
01913   // through GlobalValues. All GlobalValues have been declared at this point
01914   // so we can proceed to generate the constants.
01915   nl(Out) << "// Constant Definitions"; nl(Out);
01916   printConstants(TheModule);
01917 
01918   // Process the global variables definitions now that all the constants have
01919   // been emitted. These definitions just couple the gvars with their constant
01920   // initializers.
01921   nl(Out) << "// Global Variable Definitions"; nl(Out);
01922   for (Module::const_global_iterator I = TheModule->global_begin(),
01923          E = TheModule->global_end(); I != E; ++I) {
01924     printVariableBody(I);
01925   }
01926 
01927   // Finally, we can safely put out all of the function bodies.
01928   nl(Out) << "// Function Definitions"; nl(Out);
01929   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
01930        I != E; ++I) {
01931     if (!I->isDeclaration()) {
01932       nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
01933               << ")";
01934       nl(Out) << "{";
01935       nl(Out,1);
01936       printFunctionBody(I);
01937       nl(Out,-1) << "}";
01938       nl(Out);
01939     }
01940   }
01941 }
01942 
01943 void CppWriter::printProgram(const std::string& fname,
01944                              const std::string& mName) {
01945   Out << "#include <llvm/Pass.h>\n";
01946 
01947   Out << "#include <llvm/ADT/SmallVector.h>\n";
01948   Out << "#include <llvm/Analysis/Verifier.h>\n";
01949   Out << "#include <llvm/IR/BasicBlock.h>\n";
01950   Out << "#include <llvm/IR/CallingConv.h>\n";
01951   Out << "#include <llvm/IR/Constants.h>\n";
01952   Out << "#include <llvm/IR/DerivedTypes.h>\n";
01953   Out << "#include <llvm/IR/Function.h>\n";
01954   Out << "#include <llvm/IR/GlobalVariable.h>\n";
01955   Out << "#include <llvm/IR/IRPrintingPasses.h>\n";
01956   Out << "#include <llvm/IR/InlineAsm.h>\n";
01957   Out << "#include <llvm/IR/Instructions.h>\n";
01958   Out << "#include <llvm/IR/LLVMContext.h>\n";
01959   Out << "#include <llvm/IR/LegacyPassManager.h>\n";
01960   Out << "#include <llvm/IR/Module.h>\n";
01961   Out << "#include <llvm/Support/FormattedStream.h>\n";
01962   Out << "#include <llvm/Support/MathExtras.h>\n";
01963   Out << "#include <algorithm>\n";
01964   Out << "using namespace llvm;\n\n";
01965   Out << "Module* " << fname << "();\n\n";
01966   Out << "int main(int argc, char**argv) {\n";
01967   Out << "  Module* Mod = " << fname << "();\n";
01968   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
01969   Out << "  PassManager PM;\n";
01970   Out << "  PM.add(createPrintModulePass(&outs()));\n";
01971   Out << "  PM.run(*Mod);\n";
01972   Out << "  return 0;\n";
01973   Out << "}\n\n";
01974   printModule(fname,mName);
01975 }
01976 
01977 void CppWriter::printModule(const std::string& fname,
01978                             const std::string& mName) {
01979   nl(Out) << "Module* " << fname << "() {";
01980   nl(Out,1) << "// Module Construction";
01981   nl(Out) << "Module* mod = new Module(\"";
01982   printEscapedString(mName);
01983   Out << "\", getGlobalContext());";
01984   if (!TheModule->getTargetTriple().empty()) {
01985     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
01986             << "\");";
01987   }
01988   if (!TheModule->getTargetTriple().empty()) {
01989     nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
01990             << "\");";
01991   }
01992 
01993   if (!TheModule->getModuleInlineAsm().empty()) {
01994     nl(Out) << "mod->setModuleInlineAsm(\"";
01995     printEscapedString(TheModule->getModuleInlineAsm());
01996     Out << "\");";
01997   }
01998   nl(Out);
01999 
02000   printModuleBody();
02001   nl(Out) << "return mod;";
02002   nl(Out,-1) << "}";
02003   nl(Out);
02004 }
02005 
02006 void CppWriter::printContents(const std::string& fname,
02007                               const std::string& mName) {
02008   Out << "\nModule* " << fname << "(Module *mod) {\n";
02009   Out << "\nmod->setModuleIdentifier(\"";
02010   printEscapedString(mName);
02011   Out << "\");\n";
02012   printModuleBody();
02013   Out << "\nreturn mod;\n";
02014   Out << "\n}\n";
02015 }
02016 
02017 void CppWriter::printFunction(const std::string& fname,
02018                               const std::string& funcName) {
02019   const Function* F = TheModule->getFunction(funcName);
02020   if (!F) {
02021     error(std::string("Function '") + funcName + "' not found in input module");
02022     return;
02023   }
02024   Out << "\nFunction* " << fname << "(Module *mod) {\n";
02025   printFunctionUses(F);
02026   printFunctionHead(F);
02027   printFunctionBody(F);
02028   Out << "return " << getCppName(F) << ";\n";
02029   Out << "}\n";
02030 }
02031 
02032 void CppWriter::printFunctions() {
02033   const Module::FunctionListType &funcs = TheModule->getFunctionList();
02034   Module::const_iterator I  = funcs.begin();
02035   Module::const_iterator IE = funcs.end();
02036 
02037   for (; I != IE; ++I) {
02038     const Function &func = *I;
02039     if (!func.isDeclaration()) {
02040       std::string name("define_");
02041       name += func.getName();
02042       printFunction(name, func.getName());
02043     }
02044   }
02045 }
02046 
02047 void CppWriter::printVariable(const std::string& fname,
02048                               const std::string& varName) {
02049   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
02050 
02051   if (!GV) {
02052     error(std::string("Variable '") + varName + "' not found in input module");
02053     return;
02054   }
02055   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
02056   printVariableUses(GV);
02057   printVariableHead(GV);
02058   printVariableBody(GV);
02059   Out << "return " << getCppName(GV) << ";\n";
02060   Out << "}\n";
02061 }
02062 
02063 void CppWriter::printType(const std::string &fname,
02064                           const std::string &typeName) {
02065   Type* Ty = TheModule->getTypeByName(typeName);
02066   if (!Ty) {
02067     error(std::string("Type '") + typeName + "' not found in input module");
02068     return;
02069   }
02070   Out << "\nType* " << fname << "(Module *mod) {\n";
02071   printType(Ty);
02072   Out << "return " << getCppName(Ty) << ";\n";
02073   Out << "}\n";
02074 }
02075 
02076 bool CppWriter::runOnModule(Module &M) {
02077   TheModule = &M;
02078 
02079   // Emit a header
02080   Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
02081 
02082   // Get the name of the function we're supposed to generate
02083   std::string fname = FuncName.getValue();
02084 
02085   // Get the name of the thing we are to generate
02086   std::string tgtname = NameToGenerate.getValue();
02087   if (GenerationType == GenModule ||
02088       GenerationType == GenContents ||
02089       GenerationType == GenProgram ||
02090       GenerationType == GenFunctions) {
02091     if (tgtname == "!bad!") {
02092       if (M.getModuleIdentifier() == "-")
02093         tgtname = "<stdin>";
02094       else
02095         tgtname = M.getModuleIdentifier();
02096     }
02097   } else if (tgtname == "!bad!")
02098     error("You must use the -for option with -gen-{function,variable,type}");
02099 
02100   switch (WhatToGenerate(GenerationType)) {
02101    case GenProgram:
02102     if (fname.empty())
02103       fname = "makeLLVMModule";
02104     printProgram(fname,tgtname);
02105     break;
02106    case GenModule:
02107     if (fname.empty())
02108       fname = "makeLLVMModule";
02109     printModule(fname,tgtname);
02110     break;
02111    case GenContents:
02112     if (fname.empty())
02113       fname = "makeLLVMModuleContents";
02114     printContents(fname,tgtname);
02115     break;
02116    case GenFunction:
02117     if (fname.empty())
02118       fname = "makeLLVMFunction";
02119     printFunction(fname,tgtname);
02120     break;
02121    case GenFunctions:
02122     printFunctions();
02123     break;
02124    case GenInline:
02125     if (fname.empty())
02126       fname = "makeLLVMInline";
02127     printInline(fname,tgtname);
02128     break;
02129    case GenVariable:
02130     if (fname.empty())
02131       fname = "makeLLVMVariable";
02132     printVariable(fname,tgtname);
02133     break;
02134    case GenType:
02135     if (fname.empty())
02136       fname = "makeLLVMType";
02137     printType(fname,tgtname);
02138     break;
02139   }
02140 
02141   return false;
02142 }
02143 
02144 char CppWriter::ID = 0;
02145 
02146 //===----------------------------------------------------------------------===//
02147 //                       External Interface declaration
02148 //===----------------------------------------------------------------------===//
02149 
02150 bool CPPTargetMachine::addPassesToEmitFile(
02151     PassManagerBase &PM, raw_pwrite_stream &o, CodeGenFileType FileType,
02152     bool DisableVerify, AnalysisID StartAfter, AnalysisID StopAfter,
02153     MachineFunctionInitializer *MFInitializer) {
02154   if (FileType != TargetMachine::CGFT_AssemblyFile)
02155     return true;
02156   auto FOut = llvm::make_unique<formatted_raw_ostream>(o);
02157   PM.add(new CppWriter(std::move(FOut)));
02158   return false;
02159 }