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.
On Thu, Nov 21, 2013 at 2:30 PM, Vikas Bhargava <vikasbhargava at
gmail.com>wrote:
> Hi,
> I am trying to replace a c-style function with another function with same
> signature. Consider the following code:
>
> std::stringstream main_c;
> main_c
> <<"#include <stdio.h>\n"
> <<"extern \"C\" { \n"
> <<"int print1()\n"
> <<"{\n"
> <<" printf(\"Inside print1\\n\");\n"
> <<" return 0xdeadbeef;\n"
> <<"}\n"
> <<"int print2()\n"
> <<"{\n"
> <<" printf(\"Inside print2\\n\");\n"
> <<" return 0xbeefdead;\n"
> <<"}\n"
> <<"int mainOfLibrary(void)\n"
> <<"{\n"
> <<" return print1();\n"
> <<"}\n"
> <<"}\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(*)(void))(print1fPtr))();
> 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 );
> print1f->deleteBody();
> print1f->dropAllReferences();
> print1f->eraseFromParent();
>
> 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..
>
> thx
> Vikas.
> ======>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
<http://lists.llvm.org/pipermail/llvm-dev/attachments/20131122/85a534a0/attachment.html>