'How to get a function pointer (in order to get function address at runtime) in llvm

In C or C++, I can get the address of function func_1 at run time with the following code.

#include <stdio.h>
#include <string.h>
void func_1()
{
    printf("this is func_1\n");
}

int main()
{   
    printf("this is main\n");
    func_1();
    void *addr = (void*)func_1; // get the addr of func_1
    return 0;
}

When I convert this code to IR, I can see that the corresponding statement to get the address of the function is:

  store i8* bitcast (void ()* @func_1 to i8*), i8** %addr, align 8
  %2 = load i8*, i8** %addr, align 8
  %call1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([18 x i8], [18 x i8]* @.str.3, i64 0, i64 0), i8* %2)

Now, I want to use the LLVM compiler to use the pass optimization phase to add one such instruction for each function in the target program to get the function address. How do I achieve this? Maybe a storeInst and a loadInst, but how to set the parameters? In particular, void ()* @func_1 to i8*



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source