Search code examples
compiler-optimizationgraalvm

GraalVM: How to implement compiler optimizations?


I want to develop a tool that performs certain optimizations in a program based on the program structure. For example, let's say I want to identify if-else within a loop, and my tool shall rewrite it into two loops. I want the tool to be able to rewrite programs from a wide range of languages, example Java, C++, Python, Javascript, etc.

I am exploring if GraalVM can be used for this purpose, to act as the common platform in which I can implement the same optimizations for various languages.

Does GraalVM have a common intermediate representation (something like the LLVM IR)? I looked at the documentation but I am not sure where to get started. Any pointers?

Note: I am not looking for inter-operability between languages. You can assume that the programs I want to rewrite are written in one single language; the language may be different for different programs.


Solution

  • GraalVM has two components that are relevant for this:

    • compiler, which compiles Java bytecode to native code
    • truffle, which is a framework for implementing other programming languages on top of GraalVM.

    Languages implemented with the Truffle framework get partially evaluated to Java bytecode, which is then compiled by the Graal compiler. This article/talk gives more details including the IR used by Graal compiler: https://chrisseaton.com/truffleruby/jokerconf17/. Depending on your concrete use case you may want to hook into Truffle, Truffle partial evaluator or Graal compiler.