Inserting an external call in FunctionPass

Hi,

how do I insert a call to an external function in a FunctionPass?
My problem is with creation of the declaration for the external function.

According to http://llvm.org/docs/WritingAnLLVMPass.html#the-functionpass-class,
a FunctionPass is not supposed to add or remove functions. I assume
it's also true for function declarations.

A declaration inserted in doInitialization is cleaned up in
GlobalOptLegacyPass::runOnModule, which happens to run before my pass'
runOnFunction().

Do I need a ModulePass for this?

Hi,

how do I insert a call to an external function in a FunctionPass?
My problem is with creation of the declaration for the external function.

According to Writing an LLVM Pass — LLVM 18.0.0git documentation,
a FunctionPass is not supposed to add or remove functions. I assume
it's also true for function declarations.

A declaration inserted in doInitialization is cleaned up in
GlobalOptLegacyPass::runOnModule, which happens to run before my pass'
runOnFunction().

Do I need a ModulePass for this?

I see two possible solutions:

1. Inform the GlobalOptLegacyPass that it should not remove the function when you add it in doInitialization(). I believe adding the function to the llvm.used or llvm.compiler.used array will prevent the function from being removed. Skim the LLVM Language Reference Manual to see how to do this (LLVM Language Reference Manual — LLVM 18.0.0git documentation)

2. Make your pass a ModulePass.

Regards,

John Criswell

I think the documentation is wrong. Existing function passes frequently insert new intrinsic function declarations, and we expect that to work. The loop vectorizer also inserts calls to non-intrinsic library functions.

The intention is that function passes don’t introduce new function definitions, because then an outer pass manager would need to discover them and add them to its worklist.