Search code examples
c++clangllvmllvm-ir

How to insert a function call at the very end of the module in LLVM pass?


My pass inserts functions at certain points and those functions gather some information. At the end of the module I want to display whatever I gathered long the way, so I want to insert a function at the end of the module that will do the printing job for me. I have trouble detecting the very end of the module to insert the function right before it. Help and guidance will be appreciated!


Solution

  • I think there is no easy and simple way of doing this.You need to look for two kinds of exit points in the code.

    1) The code can have calls to functions like exit() which would be the exit point of the program. So you need to look for those in the pass and insert your function call before them. If you don't want to go through the trouble to check each and every instruction in the code, then may be you can manually replace the calls to exit() in the code function with a new exit function (something like exit_()) which contains the call to the function that you want to call followed by the actual call to the exit() function. This latter approach requires that you have access to the code beforehand.

    2) The program will exit at the end of the entry function (usually main). So, you can check if the function name is same as the potential entry point function or not and insert the function call before the return statement. If it doesn't have return statement then insert it at the end of all the instructions.