I currently have a method that does the follow: given: value, offset, stride, it adds offset to value keeping it within a group of size stride.
Examples:
20, 5, 30 => 25
29, 5, 30 => 4
42, 5, 30 => 47
And my current code is:
int cycle(int value, int offset, int stride) {
final int rem = value % stride;
return ((rem + offset) % stride - rem + value);
}
Which compiles to the following:
int cycle(int, int, int);
Code:
0: iload_1
1: iload_3
2: irem
3: istore 4
5: iload 4
7: iload_2
8: iadd
9: iload_3
10: irem
11: iload 4
13: isub
14: iload_1
15: iadd
16: ireturn
Is there any combination of code changes and / or compiler options that can make it produce something like this instead? (The example was written by hand):
int cycle(int, int, int);
Code:
0: iload_1
1: iload_3
2: irem
3: dup
4: iload_2
5: iadd
6: iload_3
7: irem
8: isub
9: iload_1
10: iadd
11: ireturn
解决方案
Most optimizing JVMs, most notably the commonly using HotSpot JVM, will transform the code into the SSA form before applying any other optimization. For this representation, it is entirely irrelevant whether the original code used temporary local variables or dup on the operand stack, the intermediate representation will be the same.
So javac doesn’t offer any option to control the byte code representation of such a construct, but it doesn’t matter anyway.