skiwi skiwi - 14 days ago 6
Java Question

Is it possible to compile to machine code in Java without an external program?

First of all, this is not your standard "I want to compile Java code to machine code" question.

I'm working on a compiler written in Java, that will translate a certain language (in my case: Brainfuck) to x86 Assembly, after that I'm currently planning to use NASM and GCC to produce machine code.

Seeing as the HotSpot JVM can compile Java bytecode to machine code, I assume there is some mechanism available to compile source code of type A to machine code.

Is there any way to use this in a compiler written in Java? My main goal is to explore the possibility of writing a compiler in Java without relying on external programs, for example GCC and NASM, being available on the path. I do need a C Compiler because I'm linking with the cstdlib as I'm using those functions in my x86 Assembly code.

Answer

Seeing as the HotSpot JVM can compile Java bytecode to machine code, I assume there is some mechanism available to compile source code of type A to machine code.

This does not follow.

The JIT compiler compiles Java bytecodes to native code. It does not understand anything other than Java bytescodes. And bytecodes are not "source code". (They are actually a form of machine code ... for an abstract computer ... a Java virtual machine.)

In short, there is no mechanism available as part of the JVM for compiling source code to machine code.

And, as it turns out, the JIT compiler is not designed for generating native code in files that something else could use. The native code is in the form of raw machine instructions in blocks of memory. No symbol tables. No relocation information. Probably full of hard-wired calls into other parts of the JVM. Basically it is designed for execution in the currently running JVM, not for anything else.

Is there any way to use this in a compiler written in Java?

The JIT compiler is not applicable to your problem ... unless you write your compiler to generate valid Java bytecodes. And if you did that, then the JVM could run your code, and the JIT compiler would at some point compile your bytecodes to native code.


Bottom line: if your goal is to generate native code that can be run as or linked to a separate executable,

  • the JIT compiler is of no use to you, but
  • you could use the JVM including the JIT compiler as your execution platform, by generating bytecodes, and
  • you could use also ordinary Java programming to implement your compiler or assembler, including a component that generates and emits native code in a format that is appropriate to your needs.
Comments