Moving a function into different module

Hi, I am trying to split a module into sub-modules. For that I would like to move certain functions into different modules. My current approach goes as follows but seems to have issues with CallInst, which I am not sure how to solve

  1. create a new Module
  2. create all functions (ie, as declarations) inside the new Module
  3. set attributes of new function (same as attributes of original)
  4. only for the selected function
    4.1. setSubprogram() (same as original one)
    4.2 splicing from the original to the new function

While the result looks alright superficially, for a function like eg

declare !optix.fsType !1 i32 @_Z5foo02v()

define i32 @_Z5foo01v() !dbg !2  {
Start:
  %0 = call i32 @_Z5foo02v(), !dbg !8
  ret i32 %0, !dbg !10
}

the result of the pointer to the function that is invoked by this CallInst seems to be still the function from the original module, incl the original’s metadata.

How is one supposed to move a function to a different module and solving these issues with function calls?

Thanks, Ali

llvm::CloneModule can correctly clone a module. If you want to see how it works, take a look at the source code.

For the particular problem you’re describing, CloneModule builds a map from globals in the old module to globals in the new module, and uses it to translate the operands of each instruction.