Skip to content

Instantly share code, notes, and snippets.

@Pikachuxxxx
Last active June 1, 2025 07:08
Show Gist options
  • Save Pikachuxxxx/b9c09d1440edb9750fe02897a9dc6afc to your computer and use it in GitHub Desktop.
Save Pikachuxxxx/b9c09d1440edb9750fe02897a9dc6afc to your computer and use it in GitHub Desktop.
ARM64 fibo asm
.section __DATA,__data
phi_const:
.double 1.618033988749895
root5_const:
.double 2.23606797749979
msg:
.asciz "Hello, ARM64 macOS!\n"
.section __TEXT,__text
.global _hello
.global _main
.global fibo
.p2align 3 // 8-byte alignment 2 ^ 3
.macro FUNC_PROLOGUE
stp x29, x30, [sp, #-16]!
mov x29, sp
.endm
.macro FUNC_EPILOGUE
ldp x29, x30, [sp], #16
ret
.endm
_hello:
FUNC_PROLOGUE
// sys_write: write(1, msg, len)
mov x0, 1 // file descriptor (stdout)
adrp x1, msg@PAGE // load page address of msg
add x1, x1, msg@PAGEOFF // load offset of msg
mov x2, 20 // length of string
mov x16, 0x4 // syscall number for write
svc 0 // trigger syscall
FUNC_EPILOGUE
_fibo:
FUNC_PROLOGUE
stp x19, x20, [sp, #-16]! // Save x19, x20 (callee-saved)
cmp x0, 1
ble .FiboBaseReturn
mov x19, x0 // Save n
sub x0, x0, 1 // n-1
bl _fibo // fibo(n-1)
mov x20, x0 // Save fibo(n-1)
sub x0, x19, 2 // n-2
bl _fibo // fibo(n-2)
add x0, x0, x20 // fibo(n-1) + fibo(n-2)
b .FiboEndFunc
.FiboBaseReturn:
// Base case: return x0 as is
.FiboEndFunc:
ldp x19, x20, [sp], #16 // Restore x19, x20
FUNC_EPILOGUE
_fibo_iterative:
FUNC_PROLOGUE
stp x19, x20, [sp, #-16]! // Save callee-saved
cmp x0, 1
ble .FiboEnd // If n <= 1, return n as is
mov x19, 0 // a = 0
mov x20, 1 // b = 1
mov x21, 2 // i = 2
.Loop:
cmp x21, x0 // while (i <= n)
bgt .FiboEnd
add x22, x19, x20 // temp = a + b
mov x19, x20 // a = b
mov x20, x22 // b = temp
add x21, x21, 1 // i++
b .Loop
.FiboEnd:
mov x0, x20 // return b
ldp x19, x20, [sp], #16
FUNC_EPILOGUE
_fibo_fast:
FUNC_PROLOGUE
stp d8, d9, [sp, #-16]! // Save callee-saved FP registers
// Load constants phi and sqrt(5)
adrp x1, phi_const@PAGE
ldr d8, [x1, phi_const@PAGEOFF]
adrp x1, root5_const@PAGE
ldr d9, [x1, root5_const@PAGEOFF]
// Prepare pow arguments: base=phi in d0, exponent=n in d1 (double)
fmov d0, d8 // d0 = phi (base)
scvtf d1, x0 // d1 = double(n) (exponent)
bl _pow // call pow(base, exponent)
// Divide result by sqrt(5)
fdiv d0, d0, d9
// Round to nearest integer
frintn d0, d0
// Convert double to int64
fcvtzs x0, d0
ldp d8, d9, [sp], #16 // Restore FP registers
FUNC_EPILOGUE
_main:
FUNC_PROLOGUE
bl _hello
mov x0, 277// calculate fibo sum upto 5 numbers
bl _fibo_fast
ldp x29, x30, [sp], #16
mov x16, 1 // exit syscall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment