Kill ModuleProvider and ghost linkage by inverting the relationship between
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
index 7e3c2ae449c012ef90683bdcd3c8b55df4d1b2cb..1f08775894941906efda561e5be86d51edf3dd5d 100644 (file)
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
 #include "llvm/TypeSymbolTable.h"
-#include "llvm/Target/TargetMachineRegistry.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/CFG.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FormattedStream.h"
+#include "llvm/Target/TargetRegistry.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Config/config.h"
 #include <algorithm>
-#include <iostream>
 #include <set>
 
 using namespace llvm;
 
 static cl::opt<std::string>
-FuncName("funcname", cl::desc("Specify the name of the generated function"),
+FuncName("cppfname", cl::desc("Specify the name of the generated function"),
          cl::value_desc("function name"));
 
 enum WhatToGenerate {
@@ -53,30 +50,32 @@ enum WhatToGenerate {
   GenType
 };
 
-static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
+static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
   cl::desc("Choose what kind of output to generate"),
   cl::init(GenProgram),
   cl::values(
-    clEnumValN(GenProgram,  "gen-program",   "Generate a complete program"),
-    clEnumValN(GenModule,   "gen-module",    "Generate a module definition"),
-    clEnumValN(GenContents, "gen-contents",  "Generate contents of a module"),
-    clEnumValN(GenFunction, "gen-function",  "Generate a function definition"),
-    clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
-    clEnumValN(GenInline,   "gen-inline",    "Generate an inline function"),
-    clEnumValN(GenVariable, "gen-variable",  "Generate a variable definition"),
-    clEnumValN(GenType,     "gen-type",      "Generate a type definition"),
+    clEnumValN(GenProgram,  "program",   "Generate a complete program"),
+    clEnumValN(GenModule,   "module",    "Generate a module definition"),
+    clEnumValN(GenContents, "contents",  "Generate contents of a module"),
+    clEnumValN(GenFunction, "function",  "Generate a function definition"),
+    clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
+    clEnumValN(GenInline,   "inline",    "Generate an inline function"),
+    clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
+    clEnumValN(GenType,     "type",      "Generate a type definition"),
     clEnumValEnd
   )
 );
 
-static cl::opt<std::string> NameToGenerate("for", cl::Optional,
+static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
   cl::desc("Specify the name of the thing to generate"),
   cl::init("!bad!"));
 
-namespace {
+extern "C" void LLVMInitializeCppBackendTarget() {
   // Register the target.
-  RegisterTarget<CPPTargetMachine> X("cpp", "  C++ backend");
+  RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
+}
 
+namespace {
   typedef std::vector<const Type*> TypeList;
   typedef std::map<const Type*,std::string> TypeMap;
   typedef std::map<const Value*,std::string> ValueMap;
@@ -88,8 +87,7 @@ namespace {
   /// CppWriter - This class is the main chunk of code that converts an LLVM
   /// module to a C++ translation unit.
   class CppWriter : public ModulePass {
-    const char* progname;
-    std::ostream &Out;
+    formatted_raw_ostream &Out;
     const Module *TheModule;
     uint64_t uniqueNum;
     TypeMap TypeNames;
@@ -104,28 +102,13 @@ namespace {
 
   public:
     static char ID;
-    explicit CppWriter(std::ostream &o) : ModulePass((intptr_t)&ID), Out(o) {}
+    explicit CppWriter(formatted_raw_ostream &o) :
+      ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
 
     virtual const char *getPassName() const { return "C++ backend"; }
 
     bool runOnModule(Module &M);
 
-    bool doInitialization(Module &M) {
-      uniqueNum = 0;
-      is_inline = false;
-
-      TypeNames.clear();
-      ValueNames.clear();
-      UnresolvedTypes.clear();
-      TypeStack.clear();
-      UsedNames.clear();
-      DefinedTypes.clear();
-      DefinedValues.clear();
-      ForwardRefs.clear();
-
-      return false;
-    }
-
     void printProgram(const std::string& fname, const std::string& modName );
     void printModule(const std::string& fname, const std::string& modName );
     void printContents(const std::string& fname, const std::string& modName );
@@ -140,7 +123,7 @@ namespace {
   private:
     void printLinkageType(GlobalValue::LinkageTypes LT);
     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
-    void printCallingConv(unsigned cc);
+    void printCallingConv(CallingConv::ID cc);
     void printEscapedString(const std::string& str);
     void printCFP(const ConstantFP* CFP);
 
@@ -150,7 +133,7 @@ namespace {
     std::string getCppName(const Value* val);
     inline void printCppName(const Value* val);
 
-    void printParamAttrs(const PAListPtr &PAL, const std::string &name);
+    void printAttributes(const AttrListPtr &PAL, const std::string &name);
     bool printTypeInternal(const Type* Ty);
     inline void printType(const Type* Ty);
     void printTypes(const Module* M);
@@ -172,7 +155,7 @@ namespace {
   };
 
   static unsigned indent_level = 0;
-  inline std::ostream& nl(std::ostream& Out, int delta = 0) {
+  inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
     Out << "\n";
     if (delta >= 0 || indent_level >= unsigned(-delta))
       indent_level += delta;
@@ -227,22 +210,18 @@ namespace {
   }
 
   void CppWriter::error(const std::string& msg) {
-    std::cerr << progname << ": " << msg << "\n";
-    exit(2);
+    llvm_report_error(msg);
   }
 
   // printCFP - Print a floating point constant .. very carefully :)
   // This makes sure that conversion to/from floating yields the same binary
   // result so that we don't lose precision.
   void CppWriter::printCFP(const ConstantFP *CFP) {
+    bool ignored;
     APFloat APF = APFloat(CFP->getValueAPF());  // copy
-    if (CFP->getType() == Type::FloatTy)
-      APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
-    Out << "ConstantFP::get(";
-    if (CFP->getType() == Type::DoubleTy)
-      Out << "Type::DoubleTy, ";
-    else
-      Out << "Type::FloatTy, ";
+    if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
+      APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
+    Out << "ConstantFP::get(getGlobalContext(), ";
     Out << "APFloat(";
 #if HAVE_PRINTF_A
     char Buffer[100];
@@ -251,7 +230,7 @@ namespace {
          !strncmp(Buffer, "-0x", 3) ||
          !strncmp(Buffer, "+0x", 3)) &&
         APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
-      if (CFP->getType() == Type::DoubleTy)
+      if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
         Out << "BitsToDouble(" << Buffer << ")";
       else
         Out << "BitsToFloat((float)" << Buffer << ")";
@@ -269,18 +248,19 @@ namespace {
            ((StrVal[0] == '-' || StrVal[0] == '+') &&
             (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
           (CFP->isExactlyValue(atof(StrVal.c_str())))) {
-        if (CFP->getType() == Type::DoubleTy)
+        if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
           Out <<  StrVal;
         else
           Out << StrVal << "f";
-      } else if (CFP->getType() == Type::DoubleTy)
-        Out << "BitsToDouble(0x" << std::hex
-            << CFP->getValueAPF().convertToAPInt().getZExtValue()
-            << std::dec << "ULL) /* " << StrVal << " */";
+      } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
+        Out << "BitsToDouble(0x"
+            << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
+            << "ULL) /* " << StrVal << " */";
       else
-        Out << "BitsToFloat(0x" << std::hex
-            << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
-            << std::dec << "U) /* " << StrVal << " */";
+        Out << "BitsToFloat(0x"
+            << utohexstr((uint32_t)CFP->getValueAPF().
+                                        bitcastToAPInt().getZExtValue())
+            << "U) /* " << StrVal << " */";
       Out << ")";
 #if HAVE_PRINTF_A
     }
@@ -288,7 +268,7 @@ namespace {
     Out << ")";
   }
 
-  void CppWriter::printCallingConv(unsigned cc){
+  void CppWriter::printCallingConv(CallingConv::ID cc){
     // Print the calling convention.
     switch (cc) {
     case CallingConv::C:     Out << "CallingConv::C"; break;
@@ -303,10 +283,20 @@ namespace {
     switch (LT) {
     case GlobalValue::InternalLinkage:
       Out << "GlobalValue::InternalLinkage"; break;
-    case GlobalValue::LinkOnceLinkage:
-      Out << "GlobalValue::LinkOnceLinkage "; break;
-    case GlobalValue::WeakLinkage:
-      Out << "GlobalValue::WeakLinkage"; break;
+    case GlobalValue::PrivateLinkage:
+      Out << "GlobalValue::PrivateLinkage"; break;
+    case GlobalValue::LinkerPrivateLinkage:
+      Out << "GlobalValue::LinkerPrivateLinkage"; break;
+    case GlobalValue::AvailableExternallyLinkage:
+      Out << "GlobalValue::AvailableExternallyLinkage "; break;
+    case GlobalValue::LinkOnceAnyLinkage:
+      Out << "GlobalValue::LinkOnceAnyLinkage "; break;
+    case GlobalValue::LinkOnceODRLinkage:
+      Out << "GlobalValue::LinkOnceODRLinkage "; break;
+    case GlobalValue::WeakAnyLinkage:
+      Out << "GlobalValue::WeakAnyLinkage"; break;
+    case GlobalValue::WeakODRLinkage:
+      Out << "GlobalValue::WeakODRLinkage"; break;
     case GlobalValue::AppendingLinkage:
       Out << "GlobalValue::AppendingLinkage"; break;
     case GlobalValue::ExternalLinkage:
@@ -317,14 +307,14 @@ namespace {
       Out << "GlobalValue::DLLExportLinkage"; break;
     case GlobalValue::ExternalWeakLinkage:
       Out << "GlobalValue::ExternalWeakLinkage"; break;
-    case GlobalValue::GhostLinkage:
-      Out << "GlobalValue::GhostLinkage"; break;
+    case GlobalValue::CommonLinkage:
+      Out << "GlobalValue::CommonLinkage"; break;
     }
   }
 
   void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
     switch (VisType) {
-    default: assert(0 && "Unknown GVar visibility");
+    default: llvm_unreachable("Unknown GVar visibility");
     case GlobalValue::DefaultVisibility:
       Out << "GlobalValue::DefaultVisibility";
       break;
@@ -356,19 +346,21 @@ namespace {
     // First, handle the primitive types .. easy
     if (Ty->isPrimitiveType() || Ty->isInteger()) {
       switch (Ty->getTypeID()) {
-      case Type::VoidTyID:   return "Type::VoidTy";
+      case Type::VoidTyID:   return "Type::getVoidTy(getGlobalContext())";
       case Type::IntegerTyID: {
         unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
-        return "IntegerType::get(" + utostr(BitWidth) + ")";
+        return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
       }
-      case Type::FloatTyID:  return "Type::FloatTy";
-      case Type::DoubleTyID: return "Type::DoubleTy";
-      case Type::LabelTyID:  return "Type::LabelTy";
+      case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
+      case Type::FloatTyID:    return "Type::getFloatTy(getGlobalContext())";
+      case Type::DoubleTyID:   return "Type::getDoubleTy(getGlobalContext())";
+      case Type::LabelTyID:    return "Type::getLabelTy(getGlobalContext())";
       default:
         error("Invalid primitive type");
         break;
       }
-      return "Type::VoidTy"; // shouldn't be returned, but make it sensible
+      // shouldn't be returned, but make it sensible
+      return "Type::getVoidTy(getGlobalContext())";
     }
 
     // Now, see if we've seen the type before and return that
@@ -434,7 +426,10 @@ namespace {
     } else {
       name = getTypePrefix(val->getType());
     }
-    name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
+    if (val->hasName())
+      name += val->getName();
+    else
+      name += utostr(uniqueNum++);
     sanitize(name);
     NameSet::iterator NI = UsedNames.find(name);
     if (NI != UsedNames.end())
@@ -447,46 +442,48 @@ namespace {
     printEscapedString(getCppName(val));
   }
 
-  void CppWriter::printParamAttrs(const PAListPtr &PAL,
+  void CppWriter::printAttributes(const AttrListPtr &PAL,
                                   const std::string &name) {
-    Out << "PAListPtr " << name << "_PAL = 0;";
+    Out << "AttrListPtr " << name << "_PAL;";
     nl(Out);
     if (!PAL.isEmpty()) {
       Out << '{'; in(); nl(Out);
-      Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
-      Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
+      Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
+      Out << "AttributeWithIndex PAWI;"; nl(Out);
       for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
-        uint16_t index = PAL.getSlot(i).Index;
-        ParameterAttributes attrs = PAL.getSlot(i).Attrs;
-        Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
-        if (attrs & ParamAttr::SExt)
-          Out << " | ParamAttr::SExt";
-        if (attrs & ParamAttr::ZExt)
-          Out << " | ParamAttr::ZExt";
-        if (attrs & ParamAttr::StructRet)
-          Out << " | ParamAttr::StructRet";
-        if (attrs & ParamAttr::InReg)
-          Out << " | ParamAttr::InReg";
-        if (attrs & ParamAttr::NoReturn)
-          Out << " | ParamAttr::NoReturn";
-        if (attrs & ParamAttr::NoUnwind)
-          Out << " | ParamAttr::NoUnwind";
-        if (attrs & ParamAttr::ByVal)
-          Out << " | ParamAttr::ByVal";
-        if (attrs & ParamAttr::NoAlias)
-          Out << " | ParamAttr::NoAlias";
-        if (attrs & ParamAttr::Nest)
-          Out << " | ParamAttr::Nest";
-        if (attrs & ParamAttr::ReadNone)
-          Out << " | ParamAttr::ReadNone";
-        if (attrs & ParamAttr::ReadOnly)
-          Out << " | ParamAttr::ReadOnly";
+        unsigned index = PAL.getSlot(i).Index;
+        Attributes attrs = PAL.getSlot(i).Attrs;
+        Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
+#define HANDLE_ATTR(X)                 \
+        if (attrs & Attribute::X)      \
+          Out << " | Attribute::" #X;  \
+        attrs &= ~Attribute::X;
+        
+        HANDLE_ATTR(SExt);
+        HANDLE_ATTR(ZExt);
+        HANDLE_ATTR(NoReturn);
+        HANDLE_ATTR(InReg);
+        HANDLE_ATTR(StructRet);
+        HANDLE_ATTR(NoUnwind);
+        HANDLE_ATTR(NoAlias);
+        HANDLE_ATTR(ByVal);
+        HANDLE_ATTR(Nest);
+        HANDLE_ATTR(ReadNone);
+        HANDLE_ATTR(ReadOnly);
+        HANDLE_ATTR(NoInline);
+        HANDLE_ATTR(AlwaysInline);
+        HANDLE_ATTR(OptimizeForSize);
+        HANDLE_ATTR(StackProtect);
+        HANDLE_ATTR(StackProtectReq);
+        HANDLE_ATTR(NoCapture);
+#undef HANDLE_ATTR
+        assert(attrs == 0 && "Unhandled attribute!");
         Out << ";";
         nl(Out);
         Out << "Attrs.push_back(PAWI);";
         nl(Out);
       }
-      Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
+      Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
       nl(Out);
       out(); nl(Out);
       Out << '}'; nl(Out);
@@ -515,7 +512,8 @@ namespace {
     if (TI != TypeStack.end()) {
       TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
       if (I == UnresolvedTypes.end()) {
-        Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
+        Out << "PATypeHolder " << typeName;
+        Out << "_fwd = OpaqueType::get(getGlobalContext());";
         nl(Out);
         UnresolvedTypes[Ty] = typeName;
       }
@@ -575,6 +573,7 @@ namespace {
         nl(Out);
       }
       Out << "StructType* " << typeName << " = StructType::get("
+          << "mod->getContext(), "
           << typeName << "_fields, /*isPacked=*/"
           << (ST->isPacked() ? "true" : "false") << ");";
       nl(Out);
@@ -614,7 +613,8 @@ namespace {
       break;
     }
     case Type::OpaqueTyID: {
-      Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
+      Out << "OpaqueType* " << typeName;
+      Out << " = OpaqueType::get(getGlobalContext());";
       nl(Out);
       break;
     }
@@ -741,33 +741,34 @@ namespace {
 
     std::string constName(getCppName(CV));
     std::string typeName(getCppName(CV->getType()));
-    if (CV->isNullValue()) {
-      Out << "Constant* " << constName << " = Constant::getNullValue("
-          << typeName << ");";
-      nl(Out);
-      return;
-    }
+
     if (isa<GlobalValue>(CV)) {
       // Skip variables and functions, we emit them elsewhere
       return;
     }
+
     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
-      Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
-          << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
-          << " \"" << CI->getValue().toStringSigned(10)  << "\", 10));";
+      std::string constValue = CI->getValue().toString(10, true);
+      Out << "ConstantInt* " << constName
+          << " = ConstantInt::get(getGlobalContext(), APInt("
+          << cast<IntegerType>(CI->getType())->getBitWidth()
+          << ", StringRef(\"" <<  constValue << "\"), 10));";
     } else if (isa<ConstantAggregateZero>(CV)) {
       Out << "ConstantAggregateZero* " << constName
           << " = ConstantAggregateZero::get(" << typeName << ");";
     } else if (isa<ConstantPointerNull>(CV)) {
       Out << "ConstantPointerNull* " << constName
-          << " = ConstanPointerNull::get(" << typeName << ");";
+          << " = ConstantPointerNull::get(" << typeName << ");";
     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
       Out << "ConstantFP* " << constName << " = ";
       printCFP(CFP);
       Out << ";";
     } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
-      if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
-        Out << "Constant* " << constName << " = ConstantArray::get(\"";
+      if (CA->isString() &&
+          CA->getType()->getElementType() ==
+              Type::getInt8Ty(CA->getContext())) {
+        Out << "Constant* " << constName <<
+               " = ConstantArray::get(getGlobalContext(), \"";
         std::string tmp = CA->getAsString();
         bool nullTerminate = false;
         if (tmp[tmp.length()-1] == 0) {
@@ -838,12 +839,12 @@ namespace {
             << getCppName(CE->getOperand(0)) << ", "
             << "&" << constName << "_indices[0], "
             << constName << "_indices.size()"
-            << " );";
+            << ");";
       } else if (CE->isCast()) {
         printConstant(CE->getOperand(0));
         Out << "Constant* " << constName << " = ConstantExpr::getCast(";
         switch (CE->getOpcode()) {
-        default: assert(0 && "Invalid cast opcode");
+        default: llvm_unreachable("Invalid cast opcode");
         case Instruction::Trunc: Out << "Instruction::Trunc"; break;
         case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
         case Instruction::SExt:  Out << "Instruction::SExt"; break;
@@ -867,8 +868,11 @@ namespace {
         Out << "Constant* " << constName << " = ConstantExpr::";
         switch (CE->getOpcode()) {
         case Instruction::Add:    Out << "getAdd(";  break;
+        case Instruction::FAdd:   Out << "getFAdd(";  break;
         case Instruction::Sub:    Out << "getSub("; break;
+        case Instruction::FSub:   Out << "getFSub("; break;
         case Instruction::Mul:    Out << "getMul("; break;
+        case Instruction::FMul:   Out << "getFMul("; break;
         case Instruction::UDiv:   Out << "getUDiv("; break;
         case Instruction::SDiv:   Out << "getSDiv("; break;
         case Instruction::FDiv:   Out << "getFDiv("; break;
@@ -969,21 +973,20 @@ namespace {
     nl(Out);
     printType(GV->getType());
     if (GV->hasInitializer()) {
-      ConstantInit = GV->getInitializer();
+      Constant *Init = GV->getInitializer();
       printType(Init->getType());
-      if (FunctionF = dyn_cast<Function>(Init)) {
+      if (Function *F = dyn_cast<Function>(Init)) {
         nl(Out)<< "/ Function Declarations"; nl(Out);
         printFunctionHead(F);
       } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
         nl(Out) << "// Global Variable Declarations"; nl(Out);
         printVariableHead(gv);
-      } else  {
-        nl(Out) << "// Constant Definitions"; nl(Out);
-        printConstant(gv);
-      }
-      if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
+        
         nl(Out) << "// Global Variable Definitions"; nl(Out);
         printVariableBody(gv);
+      } else  {
+        nl(Out) << "// Constant Definitions"; nl(Out);
+        printConstant(Init);
       }
     }
   }
@@ -991,13 +994,13 @@ namespace {
   void CppWriter::printVariableHead(const GlobalVariable *GV) {
     nl(Out) << "GlobalVariable* " << getCppName(GV);
     if (is_inline) {
-      Out << " = mod->getGlobalVariable(";
+      Out << " = mod->getGlobalVariable(getGlobalContext(), ";
       printEscapedString(GV->getName());
       Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
       nl(Out) << "if (!" << getCppName(GV) << ") {";
       in(); nl(Out) << getCppName(GV);
     }
-    Out << " = new GlobalVariable(";
+    Out << " = new GlobalVariable(/*Module=*/*mod, ";
     nl(Out) << "/*Type=*/";
     printCppName(GV->getType()->getElementType());
     Out << ",";
@@ -1012,8 +1015,7 @@ namespace {
     }
     nl(Out) << "/*Name=*/\"";
     printEscapedString(GV->getName());
-    Out << "\",";
-    nl(Out) << "mod);";
+    Out << "\");";
     nl(Out);
 
     if (GV->hasSection()) {
@@ -1085,9 +1087,13 @@ namespace {
     }
 
     switch (I->getOpcode()) {
+    default:
+      error("Invalid instruction");
+      break;
+
     case Instruction::Ret: {
       const ReturnInst* ret =  cast<ReturnInst>(I);
-      Out << "ReturnInst::Create("
+      Out << "ReturnInst::Create(getGlobalContext(), "
           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
       break;
     }
@@ -1095,9 +1101,9 @@ namespace {
       const BranchInst* br = cast<BranchInst>(I);
       Out << "BranchInst::Create(" ;
       if (br->getNumOperands() == 3 ) {
-        Out << opNames[0] << ", "
+        Out << opNames[2] << ", "
             << opNames[1] << ", "
-            << opNames[2] << ", ";
+            << opNames[0] << ", ";
 
       } else if (br->getNumOperands() == 1) {
         Out << opNames[0] << ", ";
@@ -1108,13 +1114,13 @@ namespace {
       break;
     }
     case Instruction::Switch: {
-      const SwitchInst* sw = cast<SwitchInst>(I);
+      const SwitchInst *SI = cast<SwitchInst>(I);
       Out << "SwitchInst* " << iName << " = SwitchInst::Create("
           << opNames[0] << ", "
           << opNames[1] << ", "
-          << sw->getNumCases() << ", " << bbname << ");";
+          << SI->getNumCases() << ", " << bbname << ");";
       nl(Out);
-      for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
+      for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
         Out << iName << "->addCase("
             << opNames[i] << ", "
             << opNames[i+1] << ");";
@@ -1122,6 +1128,17 @@ namespace {
       }
       break;
     }
+    case Instruction::IndirectBr: {
+      const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
+      Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
+          << opNames[0] << ", " << IBI->getNumDestinations() << ");";
+      nl(Out);
+      for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
+        Out << iName << "->addDestination(" << opNames[i] << ");";
+        nl(Out);
+      }
+      break;
+    }
     case Instruction::Invoke: {
       const InvokeInst* inv = cast<InvokeInst>(I);
       Out << "std::vector<Value*> " << iName << "_params;";
@@ -1141,8 +1158,8 @@ namespace {
       nl(Out) << iName << "->setCallingConv(";
       printCallingConv(inv->getCallingConv());
       Out << ");";
-      printParamAttrs(inv->getParamAttrs(), iName);
-      Out << iName << "->setParamAttrs(" << iName << "_PAL);";
+      printAttributes(inv->getAttributes(), iName);
+      Out << iName << "->setAttributes(" << iName << "_PAL);";
       nl(Out);
       break;
     }
@@ -1151,14 +1168,18 @@ namespace {
           << bbname << ");";
       break;
     }
-    case Instruction::Unreachable:{
+    case Instruction::Unreachable: {
       Out << "new UnreachableInst("
+          << "getGlobalContext(), "
           << bbname << ");";
       break;
     }
     case Instruction::Add:
+    case Instruction::FAdd:
     case Instruction::Sub:
+    case Instruction::FSub:
     case Instruction::Mul:
+    case Instruction::FMul:
     case Instruction::UDiv:
     case Instruction::SDiv:
     case Instruction::FDiv:
@@ -1171,11 +1192,14 @@ namespace {
     case Instruction::Shl:
     case Instruction::LShr:
     case Instruction::AShr:{
-      Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
+      Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
       switch (I->getOpcode()) {
       case Instruction::Add: Out << "Instruction::Add"; break;
+      case Instruction::FAdd: Out << "Instruction::FAdd"; break;
       case Instruction::Sub: Out << "Instruction::Sub"; break;
+      case Instruction::FSub: Out << "Instruction::FSub"; break;
       case Instruction::Mul: Out << "Instruction::Mul"; break;
+      case Instruction::FMul: Out << "Instruction::FMul"; break;
       case Instruction::UDiv:Out << "Instruction::UDiv"; break;
       case Instruction::SDiv:Out << "Instruction::SDiv"; break;
       case Instruction::FDiv:Out << "Instruction::FDiv"; break;
@@ -1196,7 +1220,7 @@ namespace {
       break;
     }
     case Instruction::FCmp: {
-      Out << "FCmpInst* " << iName << " = new FCmpInst(";
+      Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
       switch (cast<FCmpInst>(I)->getPredicate()) {
       case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
       case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
@@ -1218,11 +1242,11 @@ namespace {
       }
       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
       printEscapedString(I->getName());
-      Out << "\", " << bbname << ");";
+      Out << "\");";
       break;
     }
     case Instruction::ICmp: {
-      Out << "ICmpInst* " << iName << " = new ICmpInst(";
+      Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
       switch (cast<ICmpInst>(I)->getPredicate()) {
       case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
       case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
@@ -1238,26 +1262,7 @@ namespace {
       }
       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
       printEscapedString(I->getName());
-      Out << "\", " << bbname << ");";
-      break;
-    }
-    case Instruction::Malloc: {
-      const MallocInst* mallocI = cast<MallocInst>(I);
-      Out << "MallocInst* " << iName << " = new MallocInst("
-          << getCppName(mallocI->getAllocatedType()) << ", ";
-      if (mallocI->isArrayAllocation())
-        Out << opNames[0] << ", " ;
-      Out << "\"";
-      printEscapedString(mallocI->getName());
-      Out << "\", " << bbname << ");";
-      if (mallocI->getAlignment())
-        nl(Out) << iName << "->setAlignment("
-            << mallocI->getAlignment() << ");";
-      break;
-    }
-    case Instruction::Free: {
-      Out << "FreeInst* " << iName << " = new FreeInst("
-          << getCppName(I->getOperand(0)) << ", " << bbname << ");";
+      Out << "\");";
       break;
     }
     case Instruction::Alloca: {
@@ -1285,7 +1290,7 @@ namespace {
     }
     case Instruction::Store: {
       const StoreInst* store = cast<StoreInst>(I);
-      Out << "StoreInst* " << iName << " = new StoreInst("
+      Out << " new StoreInst("
           << opNames[0] << ", "
           << opNames[1] << ", "
           << (store->isVolatile() ? "true" : "false")
@@ -1371,7 +1376,7 @@ namespace {
     }
     case Instruction::Call:{
       const CallInst* call = cast<CallInst>(I);
-      if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
+      if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
         Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
             << getCppName(ila->getFunctionType()) << ", \""
             << ila->getAsmString() << "\", \""
@@ -1404,8 +1409,8 @@ namespace {
       nl(Out) << iName << "->setTailCall("
           << (call->isTailCall() ? "true":"false");
       Out << ");";
-      printParamAttrs(call->getParamAttrs(), iName);
-      Out << iName << "->setParamAttrs(" << iName << "_PAL);";
+      printAttributes(call->getAttributes(), iName);
+      Out << iName << "->setAttributes(" << iName << "_PAL);";
       nl(Out);
       break;
     }
@@ -1458,6 +1463,40 @@ namespace {
       Out << "\", " << bbname << ");";
       break;
     }
+    case Instruction::ExtractValue: {
+      const ExtractValueInst *evi = cast<ExtractValueInst>(I);
+      Out << "std::vector<unsigned> " << iName << "_indices;";
+      nl(Out);
+      for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
+        Out << iName << "_indices.push_back("
+            << evi->idx_begin()[i] << ");";
+        nl(Out);
+      }
+      Out << "ExtractValueInst* " << getCppName(evi)
+          << " = ExtractValueInst::Create(" << opNames[0]
+          << ", "
+          << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
+      printEscapedString(evi->getName());
+      Out << "\", " << bbname << ");";
+      break;
+    }
+    case Instruction::InsertValue: {
+      const InsertValueInst *ivi = cast<InsertValueInst>(I);
+      Out << "std::vector<unsigned> " << iName << "_indices;";
+      nl(Out);
+      for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
+        Out << iName << "_indices.push_back("
+            << ivi->idx_begin()[i] << ");";
+        nl(Out);
+      }
+      Out << "InsertValueInst* " << getCppName(ivi)
+          << " = InsertValueInst::Create(" << opNames[0]
+          << ", " << opNames[1] << ", "
+          << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
+      printEscapedString(ivi->getName());
+      Out << "\", " << bbname << ");";
+      break;
+    }
   }
   DefinedValues.insert(I);
   nl(Out);
@@ -1585,18 +1624,18 @@ namespace {
       Out << ");";
       nl(Out);
     }
-    if (F->hasCollector()) {
+    if (F->hasGC()) {
       printCppName(F);
-      Out << "->setCollector(\"" << F->getCollector() << "\");";
+      Out << "->setGC(\"" << F->getGC() << "\");";
       nl(Out);
     }
     if (is_inline) {
       Out << "}";
       nl(Out);
     }
-    printParamAttrs(F->getParamAttrs(), getCppName(F));
+    printAttributes(F->getAttributes(), getCppName(F));
     printCppName(F);
-    Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
+    Out << "->setAttributes(" << getCppName(F) << "_PAL);";
     nl(Out);
   }
 
@@ -1632,7 +1671,8 @@ namespace {
     for (Function::const_iterator BI = F->begin(), BE = F->end();
          BI != BE; ++BI) {
       std::string bbname(getCppName(BI));
-      Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
+      Out << "BasicBlock* " << bbname <<
+             " = BasicBlock::Create(getGlobalContext(), \"";
       if (BI->hasName())
         printEscapedString(BI->getName());
       Out << "\"," << getCppName(BI->getParent()) << ",0);";
@@ -1751,6 +1791,7 @@ namespace {
 
   void CppWriter::printProgram(const std::string& fname,
                                const std::string& mName) {
+    Out << "#include <llvm/LLVMContext.h>\n";
     Out << "#include <llvm/Module.h>\n";
     Out << "#include <llvm/DerivedTypes.h>\n";
     Out << "#include <llvm/Constants.h>\n";
@@ -1760,22 +1801,21 @@ namespace {
     Out << "#include <llvm/BasicBlock.h>\n";
     Out << "#include <llvm/Instructions.h>\n";
     Out << "#include <llvm/InlineAsm.h>\n";
+    Out << "#include <llvm/Support/FormattedStream.h>\n";
     Out << "#include <llvm/Support/MathExtras.h>\n";
     Out << "#include <llvm/Pass.h>\n";
     Out << "#include <llvm/PassManager.h>\n";
+    Out << "#include <llvm/ADT/SmallVector.h>\n";
     Out << "#include <llvm/Analysis/Verifier.h>\n";
     Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
     Out << "#include <algorithm>\n";
-    Out << "#include <iostream>\n\n";
     Out << "using namespace llvm;\n\n";
     Out << "Module* " << fname << "();\n\n";
     Out << "int main(int argc, char**argv) {\n";
     Out << "  Module* Mod = " << fname << "();\n";
     Out << "  verifyModule(*Mod, PrintMessageAction);\n";
-    Out << "  std::cerr.flush();\n";
-    Out << "  std::cout.flush();\n";
     Out << "  PassManager PM;\n";
-    Out << "  PM.add(new PrintModulePass(&llvm::cout));\n";
+    Out << "  PM.add(createPrintModulePass(&outs()));\n";
     Out << "  PM.run(*Mod);\n";
     Out << "  return 0;\n";
     Out << "}\n\n";
@@ -1786,7 +1826,9 @@ namespace {
                               const std::string& mName) {
     nl(Out) << "Module* " << fname << "() {";
     nl(Out,1) << "// Module Construction";
-    nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
+    nl(Out) << "Module* mod = new Module(\"";
+    printEscapedString(mName);
+    Out << "\", getGlobalContext());";
     if (!TheModule->getTargetTriple().empty()) {
       nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
     }
@@ -1819,7 +1861,9 @@ namespace {
   void CppWriter::printContents(const std::string& fname,
                                 const std::string& mName) {
     Out << "\nModule* " << fname << "(Module *mod) {\n";
-    Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
+    Out << "\nmod->setModuleIdentifier(\"";
+    printEscapedString(mName);
+    Out << "\");\n";
     printModuleBody();
     Out << "\nreturn mod;\n";
     Out << "\n}\n";
@@ -1962,9 +2006,9 @@ char CppWriter::ID = 0;
 //===----------------------------------------------------------------------===//
 
 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
-                                                std::ostream &o,
+                                                formatted_raw_ostream &o,
                                                 CodeGenFileType FileType,
-                                                bool Fast) {
+                                                CodeGenOpt::Level OptLevel) {
   if (FileType != TargetMachine::AssemblyFile) return true;
   PM.add(new CppWriter(o));
   return false;