Skip to content

Commit e91967c

Browse files
committed
making the x86_64 code neater and commenting more
1 parent da41db5 commit e91967c

File tree

1 file changed

+22
-40
lines changed

1 file changed

+22
-40
lines changed

contents/euclidean_algorithm/code/asm-x64/euclidean_example.s

Lines changed: 22 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -7,86 +7,68 @@
77
.global main
88
.extern printf
99

10+
# rdi - a
11+
# rsi - b
12+
# RET rax - gcd of a and b
1013
euclid_mod:
11-
# Abs of the first argument
12-
mov rax, rdi
14+
mov rax, rdi # Get abs of a
1315
sar rax, 31
1416
xor rdi, rax
1517
sub rdi, rax
16-
17-
# Abs of the second argument
18-
mov rax, rsi
18+
mov rax, rsi # Get abs of b
1919
sar rax, 31
2020
xor rsi, rax
2121
sub rsi, rax
22-
23-
# While loop
2422
jmp mod_check
2523
mod_loop:
26-
xor rdx, rdx
24+
xor rdx, rdx # Take the mod of a and b
2725
mov rax, rdi
2826
div rsi
29-
mov rdi, rsi
30-
mov rsi, rdx
27+
mov rdi, rsi # Set b to the mod of a and b
28+
mov rsi, rdx # Set a to b
3129
mod_check:
32-
cmp rsi, 0
30+
cmp rsi, 0 # Check if b is non-zero
3331
jne mod_loop
34-
35-
mov rax, rdi
32+
mov rax, rdi # Return the result
3633
ret
3734

3835
euclid_sub:
39-
# Abs of the first argument
40-
mov rax, rdi
36+
mov rax, rdi # Get abs of a
4137
sar rax, 31
4238
xor rdi, rax
4339
sub rdi, rax
44-
45-
# Abs of the second argument
46-
mov rax, rsi
40+
mov rax, rsi # Get abs of b
4741
sar rax, 31
4842
xor rsi, rax
4943
sub rsi, rax
50-
51-
# While loop
5244
jmp check
5345
loop:
54-
cmp rdi, rsi
46+
cmp rdi, rsi # Find which is bigger
5547
jle if_true
56-
57-
sub rdi, rsi
48+
sub rdi, rsi # If a is bigger then a -= b
5849
jmp check
5950
if_true:
60-
sub rsi, rdi
51+
sub rsi, rdi # Else b -= a
6152
check:
62-
cmp rsi, rdi
53+
cmp rsi, rdi # Check if a and b are not equal
6354
jne loop
64-
65-
mov rax, rdi
55+
mov rax, rdi # Return results
6656
ret
6757

6858
main:
69-
# Calling euclid_mod
70-
mov rdi, 4288
59+
mov rdi, 4288 # Call euclid_mod
7160
mov rsi, 5184
7261
call euclid_mod
73-
74-
# Printing euclid_mod output
75-
mov rdi, OFFSET fmt
62+
mov rdi, OFFSET fmt # Print output
7663
mov rsi, rax
7764
xor rax, rax
7865
call printf
79-
80-
# Calling euclid_sub
81-
mov rdi, 1536
66+
mov rdi, 1536 # Call euclid_sub
8267
mov rsi, 9856
8368
call euclid_sub
84-
85-
# Printing euclid_sub output
86-
mov rdi, OFFSET fmt
69+
mov rdi, OFFSET fmt # Print output
8770
mov rsi, rax
8871
xor rax, rax
8972
call printf
90-
91-
xor rax, rax
73+
xor rax, rax # Return 0
9274
ret

0 commit comments

Comments
 (0)