ReturnInfinity / BareMetal-OS-legacy

BareMetal is a 64-bit OS for x86-64 based computers. The OS is written entirely in Assembly while applications can be written in Assembly, C/C++, and Rust.
1.74k stars 303 forks source link

Optimisation #118

Closed faissaloo closed 7 years ago

faissaloo commented 7 years ago

Some really basic optimisations, mostly:
cmp <reg>, 0 -> test <reg>, <reg>
mov <reg>, 0 -> xor <reg>, <reg>
sub <reg/mem>, 1 -> dec <reg/mem>
inc <reg/mem>, 1 -> add <reg/mem>

sub <reg/mem>, 1
cmp <reg/mem>, 0

-> dec <reg/mem>

IanSeyler commented 7 years ago

I had a reason for this back when initially writing this code as I came across something that said inc/dec should not be used in x86-64. I can't recall where I saw this but this would cut down on compiled code size.

IanSeyler commented 7 years ago

Thanks for submitting this! I've also made the appropriate changes to BareMetal-kernel based on this pull request.

faissaloo commented 7 years ago

No problem, glad to help!

effbiae commented 7 years ago

if you're interested in seeing how gcc optimizes a small function:

$ cat t.c && for x in O2 Os; do (gcc -$x -c t.c && objdump -d -Mintel t.o |sed -ne '/._

/,/^$/p');done int main(long c, char__v) { long i,r=0; while(c--) { if(v[c]!=0) r+=(long)v[c]; if(c==0) break; } return r; } 0000000000000000
: 0: 31 c0 xor eax,eax 2: 48 85 ff test rdi,rdi 5: 75 02 jne 9 <main+0x9> 7: f3 c3 repz ret 9: 48 03 44 fe f8 add rax,QWORD PTR [rsi+rdi_8-0x8] e: 48 83 ef 01 sub rdi,0x1 12: 74 f3 je 7 <main+0x7> 14: 48 03 44 fe f8 add rax,QWORD PTR [rsi+rdi_8-0x8] 19: 48 83 ef 01 sub rdi,0x1 1d: 75 ea jne 9 <main+0x9> 1f: eb e6 jmp 7 <main+0x7> 0000000000000000
: 0: 31 c0 xor eax,eax 2: 48 85 ff test rdi,rdi 5: 74 0a je 11 <main+0x11> 7: 48 03 44 fe f8 add rax,QWORD PTR [rsi+rdi_8-0x8] c: 48 ff cf dec rdi f: eb f4 jmp 5 <main+0x5> 11: c3 ret

  • use xor instead of mov x,0
  • use test instead of cmp x,0
  • for smaller code, use dec x otherwise sub x,1 for speed

On 12 October 2016 at 04:44, Ian Seyler notifications@github.com wrote:

I had a reason for this back when initially writing this code as I came across something that said inc/dec should not be used in x86-64. I can't recall where I saw this but this would cut down on compiled code size.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/ReturnInfinity/BareMetal-OS/pull/118#issuecomment-252990778, or mute the thread https://github.com/notifications/unsubscribe-auth/AAn-H9vOG_b_IeJFivYQDtbW5wB6xszWks5qy8sBgaJpZM4KRb2J .