練習: bcを読んで書くだけ

llvm-as,disを参考に。エラー処理等々は無視。

idchange.cpp

#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
#include 
#include 
#include 
using namespace llvm;

static cl::opt
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt
OutputFilename("o", cl::desc("Override output filename"),
               cl::value_desc("filename"));

int main(int argc, char **argv) {
  llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
  cl::ParseCommandLineOptions(argc, argv, "");
  std::auto_ptr M;
  std::string ErrorMessage;

  if (MemoryBuffer *Buffer
      = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
      M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
      delete Buffer;
  }

  std::ostream *Out = 0;
  Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
                                std::ios::trunc | std::ios::binary);
  WriteBitcodeToFile(M.get(), *Out);
  delete Out;

  return 0;
}

ビルド

c++ -g idchange.cpp `llvm-config --cxxflags --ldflags --libs core --libs bitwriter --libs bitreader` -o idchange

サンプルソース(sample.cpp)

int foo(int i) {
    return 0;
}

int bar(int i, char c) {
    return 0;
}

実行(sample.bcを呼んでsapmole.bcを書き出すだけ)

llvm-gcc --emit-llvm -S sample.cpp -o sample.ll
llvm-as -f sample.ll -o sample.bc
./idchange sample.bc -o sample2.bc

sample.bcとsample2.bcではdiffがでる。

.llに戻して確かめると、以下のようなdiffがあった。

< ; ModuleID = 'sample.cpp'
    • -
> ; ModuleID = 'sample2.bc'