-
-
Save MrSmith33/08e28a8b33650df314d35feeecb497cb to your computer and use it in GitHub Desktop.
Demonstration of if/else jump optimization (removes extra jump)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
i32 sign(i32 number) { | |
i32 result; | |
if (number < 0) result = 0-1; | |
else if (number > 0) result = 1; | |
else result = 0; | |
return result; | |
} | |
83 F9 00 0F 8C 05 00 00 00 E9 0A 00 00 00 B8 FF | |
FF FF FF E9 1D 00 00 00 83 F9 00 0F 8F 05 00 00 | |
00 E9 0A 00 00 00 B8 01 00 00 00 E9 05 00 00 00 | |
B8 00 00 00 00 C3 | |
0: 83 f9 00 cmp ecx,0x0 ; compare | |
3: 0f 8c 05 00 00 00 jl 0xe ; jump to @then1 if true | |
9: e9 0a 00 00 00 jmp 0x18 ; jump to @else1 | |
e: b8 ff ff ff ff mov eax,0xffffffff ; @then1 | |
13: e9 1d 00 00 00 jmp 0x35 ; | |
18: 83 f9 00 cmp ecx,0x0 ; @else1 | |
1b: 0f 8f 05 00 00 00 jg 0x26 ; jump to @then2 if true | |
21: e9 0a 00 00 00 jmp 0x30 ; jump to @else2 | |
26: b8 01 00 00 00 mov eax,0x1 ; @then2 | |
2b: e9 05 00 00 00 jmp 0x35 ; | |
30: b8 00 00 00 00 mov eax,0x0 ; @else2 | |
35: c3 ret ; | |
// With condition inversion and then/else inversion | |
83 F9 00 0F 8D 0A 00 00 00 B8 FF FF FF FF E9 18 | |
00 00 00 83 F9 00 0F 8E 0A 00 00 00 B8 01 00 00 | |
00 E9 05 00 00 00 B8 00 00 00 00 C3 | |
0: 83 f9 00 cmp ecx,0x0 ; compare | |
3: 0f 8d 0a 00 00 00 jge 0x13 ; jump to @else1 if false | |
9: b8 ff ff ff ff mov eax,0xffffffff ; @then1 (no jmp because it is next instruction) | |
e: e9 18 00 00 00 jmp 0x2b ; | |
13: 83 f9 00 cmp ecx,0x0 ; @else1 | |
16: 0f 8e 0a 00 00 00 jle 0x26 ; jump to @else2 if false | |
1c: b8 01 00 00 00 mov eax,0x1 ; @then2 (no jmp because it is next instruction) | |
21: e9 05 00 00 00 jmp 0x2b ; | |
26: b8 00 00 00 00 mov eax,0x0 ; @else2 | |
2b: c3 ret ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment