Replacing C-style function

I am trying to replace a c-style function with another function with same signature. Consider the following code:

std::stringstream main_c;
<<"#include <stdio.h>\n"
<<“extern “C” { \n”
<<“int print1()\n”
<<" printf(“Inside print1\n”);\n"
<<" return 0xdeadbeef;\n"
<<“int print2()\n”
<<" printf(“Inside print2\n”);\n"
<<" return 0xbeefdead;\n"
<<“int mainOfLibrary(void)\n”
<<" return print1();\n"

I compile this into an llvm::Module (say main) correctly and then create and execution engine out of it:

std::string errMsg;
llvm::ExecutionEngine *ee =
llvm::EngineBuilder( main.get() ).setErrorStr( &errMsg ).create();
ASSERT_NE( ee, nullptr )<<“Execution engine is nullptr:”<<errMsg;

At this point, I am able to retrieve pointers to all the 3 functions (print1, print2 and mainOfLibrary) correctly and execute them as well, e.g:

//check the print1f is behaving properly
llvm::Function *print1f = main->getFunction( “print1” );
ASSERT_NE( print1f, nullptr );
void print1fPtr = ee->getPointerToFunction( print1f );
int ret = ((int(
EXPECT_EQ(0xdeadbeef, ret);

However, when i try to replace the use of print1 with print2, it doesn’t seem to work correctly. This is the sequence of steps that I am following:

llvm::Function *print2f = main->getFunction( “print2” );

print2f->takeName( print1f );

llvm::Function *mainf = main->getFunction( “mainOfLibrary” );

ee->freeMachineCodeForFunction( mainf );
ee->freeMachineCodeForFunction( print1f );

print1f->replaceAllUsesWith( print2f );

mainfPtr = ee->recompileAndRelinkFunction( mainf );
ASSERT_NE( mainfPtr, nullptr );
ret = ((int(*)(void))(mainfPtr))();
EXPECT_EQ(0xbeefdead, ret);

Can you please let me know if I am missing something in the steps above. Does the “extern C” in the code snippet make any difference? I am doing that to avoid name mangling of the 3 functions…


figured that print1 was inlined in main and therefore could not be “replaced” by print2. Added attributes to print1 to disable its inlining and now the code works.