[llvm-dev] How to get return address at llvm ir level?

Bekket McClane via llvm-dev llvm-dev at lists.llvm.org
Tue Sep 4 19:47:13 PDT 2018



> On Sep 4, 2018, at 10:16 PM, PenYiWang via llvm-dev <llvm-dev at lists.llvm.org> wrote:
> 
> Hi
> 
> I want to write a FunctionPass to insert some code before return.
> 
> Funcion:
> ..
> ..
> ..
> mov eax,[esp]
> cmp eax,0x12345678
> je 0x12345678
> ret
> (maybe stack will not balance)
> 
> I wonder that can I get the return address at llvm ir level?

Short answer: You can’t 

Long answer: LLVM IR is a high level description, in comparison to assembly code, of a program.
It “tries" to describe programs in a platform-independent fashion. However, return address, even how a function pass its return data, is really platform and architecture specific. 

Nevertheless, your goal can still be achieved easily in LLVM. In your cases, just iterates over all the instructions in a Function, find the return instructions(i.e. those who are ReturnInst class instances), and insert the desired things before them.
Of course, taking care of the data dependencies and/or control dependencies when you insert instructions


> 
> I use IRBuilder to CreateICmpEQ and CreateCondBr.

This combination is for branches between BasicBlocks, not function returns.

> 
> but I don't how to get the value of return addrss.
> 
> I have found there is a  Intrinsic::returnaddress.
> 
> Is Intrinsic::returnaddress can help me?

Intrinsic functions in LLVM are usually used for special purposes. I’m certainly sure that this Intrinsic::returnaddress is not what you want. Since it won’t be generated by normal compiler frontend, and it would only place a function call in IR without invoking it and gives you return address **when you’re doing code optimizations**

> 
> I don't konw how to use Intrinsic::returnaddress because few files use this intrinsic.

LLVM IR is neither (machine) assembly code nor something with the same role as assembly code - It's a representation for, and should only be used for compiler optimizations.
My suggestion is to read the official documents about [what is LLVM IR](https://llvm.org/docs/LangRef.html#abstract <https://llvm.org/docs/LangRef.html#abstract> ). It’s a nice introduction and it’s not long.

Best,
Bekket

> 
> Thanks
> 
> 
> _______________________________________________
> LLVM Developers mailing list
> llvm-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20180904/de1f6cc6/attachment.html>


More information about the llvm-dev mailing list