[llvm-dev] How to extract functions from Module A and put them into Module B, and generate a new IR file?

shen Liu via llvm-dev llvm-dev at lists.llvm.org
Thu Mar 22 11:28:04 PDT 2018


Hi all,

This is Michael and very happy to share my question here!

My question is, is there a way to "extract" a function from Module A and
write it into another Module B, and generate two new IR files? IRBuilder
seems like a workable way but I have to create instructions one by one. I
am new to LLVM so don't know whether it is doable, here is my experimental
code:

runOnModule(Module &M){
  ...

  LLVMContext& context = getGlobalContext();

  llvm::raw_fd_ostream osA("A.bc", "", llvm::sys::fs::F_None);
  llvm::raw_fd_ostream osB("B.bc", "", llvm::sys::fs::F_None);

  llvm::Module *ModuleA = new llvm::Module("A", context);
  llvm::Module *ModuleB = new llvm::Module("B", context);

  ModuleA->setDataLayout(M.getDataLayout());
  ModuleA-->setTargetTriple(M.getTargetTriple());
  ModuleA-->setModuleInlineAsm(M.getModuleInlineAsm());

  ModuleB-->setDataLayout(M.getDataLayout());
  ModuleB-->setTargetTriple(M.getTargetTriple());
  ModuleB-->setModuleInlineAsm(M.getModuleInlineAsm());

  for (Function &F : M) {
      if (F.getName() == "My Criterion")
          ModuleA->getFunctionList().push_back(F);
      else
          ModuleB->getFunctionList().push_back(F);
  }

  WriteBitcodeToFile(ModuleA, osA);
  WriteBitcodeToFile(ModuleB, osB);

}


By doing this I can get two .bc files, but when I open it, for each
function I can only get the declaration, but not the definition(function
body).

Could you give me some comments on how to generate the function
definitions? Or any other better ways for generating the IRs? Thanks very
much!

Best regards,

Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20180322/25d9e2f4/attachment.html>


More information about the llvm-dev mailing list