How to create a function pointer pointing to a function and returning it in IR code?

323 Views Asked by At

I have the code ready in an Transforms/Instrumentation, which would intercept my original code.I would like to use function pointer pointing to an original function (recursion). Instead of returning an original function directly at run time, i would like to use function pointer variable returning(the function pointer part should be in LLVM IR code).

I cannot find any example code. I have tried getOrInsertFunction function to create a new function pointer looks like this API is used to insert a new function, not variables.

//-----------------------------------------------------

//Original Function

int find_sum(int a)

{

  if (a!=0) {

     return a + find_sum(a-1);

   }

return 0;

}

int main() {

printf("Value of find_sum is %d\n", find_sum(5));

}

//-------------------------------------------------------------------------





//Expected Function at run time through Instrumentation pass
int find_sum(int a)

{

   int (*fn_ptr)(int) = &find_sum; //should be an IR code

   if (a!=0) {

       return a + (*fn_ptr)(a-1); //should be an IR code

   }

 return 0;

}

int main() {

printf("Value of find_sum is %d\n", find_sum(5));

}
//--------------------------------------------------------
1

There are 1 best solutions below

0
arnt On

A function pointer is simply a pointer to a function; any variable (including fields in a struct) can have such a type. If you have a function f and want to store a pointer to it in a GlobalVariable, then you create the GlobalVariable with type f->getType(). A load instruction that reads from such a global variable will have a type such that you can use it as an argument to a call instruction