-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathfib.asm
90 lines (71 loc) · 996 Bytes
/
fib.asm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#
# Recursive computation of Fibonacci numbers
#
.data;
PROMPT_STR: .stringz "Input an integer:\n";
# Code section
.code;
push PROMPT_STR;
syscall print_str;
# Read input number
call READ_INT, 0;
# Call FIB with 1 argument
call FIB, 1;
# Print the result
syscall print_i64;
syscall print_endl;
push 0;
ret;
#
# u64 fib(u64 n)
#
FIB:
get_arg 0;
push 2;
lt_i64;
jz _if_false_0;
get_arg 0;
ret;
_if_false_0:
get_arg 0;
push 1;
sub_u64;
call FIB, 1;
get_arg 0;
push 2;
sub_u64;
call FIB, 1;
add_u64;
ret;
#
# Read a positive integer from stdlin
#
READ_INT:
push 0; # Current integer value
LOOP:
# Read one character
syscall getchar;
# If < 0 done
dup;
push 48;
lt_i64;
jnz DONE;
# If > 9 done
dup;
push 57;
gt_i64;
jnz DONE;
# Convert to integer digit
push 48;
sub_u64;
# int_val * 10;
get_local 0;
push 10;
mul_u64;
# int_val + 10;
add_u64;
set_local 0;
jmp LOOP;
DONE:
get_local 0;
ret;