Search code examples
javajvmjvm-hotspotescape-analysis

Does Hotspot JVM perform Escape Analysis during On Stack Replacement compilation?


Consider the following code:

void methodWithOSR() {
    Foo foo = new Foo(); // this object doesn't escape
    for (int i = 0; i < 1_000_000; i++) {
        // some code that uses `foo`
    }
}

Is Hotspot JVM able to scalarize foo on the stack, when C2 OSR compilation kicks in? I suppose that it might be problematic, because a live object already exists in heap, so it might be not possible to "move" object from heap to stack and registers.


Solution

  • It's not quite clear what "scalaraize" means in this situation, but let me paraphrase the question.

    Does HotSpot JVM run Escape Analysis during OSR compilation?

    Yes. Most compiler features/optimizations are valid for OSR compilation just like for a regular compilation.

    Does HotSpot benefit from Escape Analysis with respect to "scalarization" (whatever it mean) of Foo instance here?

    The main goal of scalar replacement is allocation elimination, which is not applicable to Foo instance since the object is already allocated in heap.

    Will HotSpot move live object from heap to stack?

    No. There is no point in doing so. Stack is just another memory area.

    Can HotSpot optimize access to Foo fields here?

    Yes. It may cache fields in registers, for example, like in this case. However, the modifications will be still written back to the heap.