Video in progress

Strong Middle ⚙️ JVM and memory

What is auto-vectorization, which loops turn into SIMD instructions, and where does the Vector API fit in?

C2 can turn simple array loops (independent operations on elements of the same type) into SIMD instructions, where one instruction processes 4-16 elements at once. It doesn't work on complex loops. For explicit vector code there is the Vector API, but it is still in an incubator module.

📖 Answer

C2's SuperWord optimization turns a loop like this into AVX/NEON instructions:

// vectorizes: counted loop, arrays, independent elements
for (int i = 0; i < a.length; i++) {
    c[i] = a[i] * b[i] + 1;
}

What does not vectorize:

  • a method call inside the loop (if it isn't inlined), if branches (some get handled);
  • dependencies between iterations: a[i] = a[i-1] + x;
  • a long index (in many versions), arrays of objects, List<Integer>;
  • reductions (sum += a[i]): they work for some types, but a double sum is limited because the order of operations must not change.

It is not easy to verify: you look for instructions like vmulps and vpaddd with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly (needs hsdis) or JMH's -prof perfasm.

The Vector API (jdk.incubator.vector) is for writing vector operations explicitly:

static final VectorSpecies<Float> S = FloatVector.SPECIES_PREFERRED;
for (int i = 0; i < S.loopBound(n); i += S.length()) {
    var va = FloatVector.fromArray(S, a, i);
    var vb = FloatVector.fromArray(S, b, i);
    va.mul(vb).add(1f).intoArray(c, i);
}
// the leftover elements with an ordinary loop

It has been in incubator status since JDK 16 (waiting for Valhalla), and using it requires --add-modules jdk.incubator.vector. Keep that status in mind before using it in prod code. An ordinary backend service rarely needs this kind of optimization. In computation-heavy code like ML inference, image processing and compression it gives a noticeable gain.