llir / llvm

Library for interacting with LLVM IR in pure Go.
https://llir.github.io/document/
BSD Zero Clause License
1.16k stars 80 forks source link

How to compile LLVM IR to machine code programatically? #238

Closed kant777 closed 23 hours ago

kant777 commented 1 week ago

I understand that the library allows for the generation of LLVM IR. How can one programmatically compile the IR to machine code?

mewmew commented 4 days ago

I understand that the library allows for the generation of LLVM IR. How can one programmatically compile the IR to machine code?

Hi @kant777!

Happy to see playing around with LLVM IR.

As you mentioned, the llir/llvm library only handles read/write/modify of LLVM IR. So to compile LLVM IR to machine code one would rely on external tools.

The official LLVM toolchain contains tools for both compilation of LLVM IR to machine code and linking of LLVM IR modules.

If you want to do this programmatically, the easiest way would be to simply use the os/exec Go package and invoke the official LLVM toolchain tools to compile the LLVM IR to machine code.

Potentially using a temporary output file for the LLVM IR. If you decide to use a temporary LLVM IR output file, ensure that the permissions are set in such a way that other users cannot modify its content, as otherwise the LLVM IR code could be changed before compilation (race condition) to inject potentially malicious code.

Let me know how it works out.

Happy coding!

Cheers, Robin

kant777 commented 2 days ago

@mewmew Got it. Also Do you plan to support latest llvm versions since its been a while now? if not, it makes me think I should probably use https://github.com/twitchyliquid64/golang-asm although I loose all the optimizations that comes with the llvm compiler.

mewmew commented 23 hours ago

@mewmew Got it. Also Do you plan to support latest llvm versions since its been a while now? if not, it makes me think I should probably use https://github.com/twitchyliquid64/golang-asm although I loose all the optimizations that comes with the llvm compiler.

Hi @kant777!

While we'd love to support the latest LLVM version, as this is a hobby project driven by open source enthusiasts, there are no immediate plans for it as it requires a large amount of dedicated time.

From time to time, we feel the urge to work on the project, and then update to the latest LLVM versions (as we've done in the past).

So, I'd say, if you need anything specific from the newer versions of LLVM, then use the official tools and bindings to the C library of LLVM. Also, look into the tinygo library with bindings for LLVM, https://pkg.go.dev/tinygo.org/x/go-llvm. They should also include the ability to directly target machine code which would suit your needs quite well.

Wish you all the best and happy coding!

Cheerful summer wishes. Robin