How to extract functions from Module A and put them into Module B, and generate a new IR file?

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

Correctly moving functions between modules is tricky in general; I'd suggest using one of the existing utilities to do it. See include/llvm/Linker/Linker.h and include/llvm/Linker/IRMover.h.

-Eli