当索引的范围通过and限制时,Hotspot可以消除边界检查吗?
考虑以下函数:
int foo(int[] indices) {
int[] lookup = new int[256];
fill(lookup); // populate values, not shown
int sum = 0;
for (int i : indices) {
sum += lookup[i & 0xFF]; // array access
}
return sum;
}
现代 HotSpot 可以消除lookup[i & 0xFF]访问的边界检查吗?此访问不能越界,因为i & 0xFF范围在 0-255 之间,并且数组有 256 个元素。
回答
是的,这是一个相对简单的优化,HotSpot 绝对可以做到。JIT 编译器推断可能的表达式范围,并使用此信息来消除冗余检查。
我们可以通过打印汇编代码来验证这一点: -XX:CompileCommand=print,Test::foo
...
0x0000020285b5e230: mov r10d,dword ptr [rcx+r8*4+10h] # load 'i' from indices array
0x0000020285b5e235: and r10d,0ffh # i = i & 0xff
0x0000020285b5e23c: mov r11,qword ptr [rsp+8h] # load 'lookup' into r11
0x0000020285b5e241: add eax,dword ptr [r11+r10*4+10h] # eax += r11[i]
加载i和lookup[i & 0xff].
- Surprising to see the load into r11 there, it is invariant so shouldn't it be moved out of the loop?