Introduce LLVMWriteBitcodeToMemoryBuffer C API function.
[oota-llvm.git] / lib / Bitcode / Writer / BitWriter.cpp
index b2e7ac2ec0f02fa91093ffc13681699e9b420528..7218ea05bb5bdd651c0816429789a73fe88bba6e 100644 (file)
@@ -2,50 +2,48 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by the LLVM research group and is distributed under
-// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 
 #include "llvm-c/BitWriter.h"
 #include "llvm/Bitcode/ReaderWriter.h"
-#include "llvm/Support/CHelpers.h"
-#include <fstream>
-
+#include "llvm/IR/Module.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
 using namespace llvm;
 
 
 /*===-- Operations on modules ---------------------------------------------===*/
 
 int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path) {
-  std::ofstream OS(Path);
-  
-  if (!OS.fail())
-    WriteBitcodeToFile(unwrap(M), OS);
-  
-  if (OS.fail())
+  std::error_code EC;
+  raw_fd_ostream OS(Path, EC, sys::fs::F_None);
+
+  if (EC)
     return -1;
-  
+
+  WriteBitcodeToFile(unwrap(M), OS);
   return 0;
 }
 
-#ifdef __GNUC__
-#include <ext/stdio_filebuf.h>
+int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose,
+                         int Unbuffered) {
+  raw_fd_ostream OS(FD, ShouldClose, Unbuffered);
 
-// FIXME: Control this with configure? Provide some portable abstraction in
-// libSystem? As is, the user will just get a linker error if they use this on 
-// non-GCC. Some C++ stdlibs even have ofstream::ofstream(int fd).
-int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int FileHandle) {
-  __gnu_cxx::stdio_filebuf<char> Buffer(FileHandle, std::ios_base::out);
-  std::ostream OS(&Buffer);
-  
-  if (!OS.fail())
-    WriteBitcodeToFile(unwrap(M), OS);
-  
-  if (OS.fail())
-    return -1;
-  
+  WriteBitcodeToFile(unwrap(M), OS);
   return 0;
 }
 
-#endif
+int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int FileHandle) {
+  return LLVMWriteBitcodeToFD(M, FileHandle, true, false);
+}
+
+LLVMMemoryBufferRef LLVMWriteBitcodeToMemoryBuffer(LLVMModuleRef M) {
+  std::string Data;
+  raw_string_ostream OS(Data);
+
+  WriteBitcodeToFile(unwrap(M), OS);
+  return wrap(MemoryBuffer::getMemBufferCopy(OS.str()).release());
+}