ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Architecture / ISA > MIPS 어셈블리 스택 프레임을 이용한 재귀 함수(피보나치) 구현Implementing Recursive Functions (Fibonacci) with Stack Frames in MIPS Assembly
Architecture / ISA Advanced MIPS32 / MARS / QtSpim

MIPS 어셈블리 스택 프레임을 이용한 재귀 함수(피보나치) 구현Implementing Recursive Functions (Fibonacci) with Stack Frames in MIPS Assembly

함수 호출 시 복귀 주소($ra)와 로컬 변수($s0, $s1)를 스택 메모리에 저장·복원하여 재귀 호출(Recursion)을 안정적으로 처리하는 MIPS 어셈블리 구현 패턴입니다.A MIPS assembly pattern for handling recursion safely by saving and restoring the return address ($ra) and local preserved registers ($s0, $s1) on the stack.

#MIPS #Assembly #Recursion #Stack #Fibonacci
핵심 개념재귀 함수는 자기 자신을 다시 호출(jal)하므로, 호출 직전의 복귀 주소($ra)가 덮어써지지 않도록 스택 포인터($sp)를 감소시켜 스택 프레임에 백업해야 합니다. 또한 첫 번째 재귀 호출 동안 인자 n과 중간 결과값이 유실되지 않도록 Callee-Saved 레지스터($s0, $s1)를 함께 보존하고 복원합니다.
Key ConceptBecause a recursive function calls itself (jal), it must decrement the stack pointer ($sp) and save the current return address ($ra) in a stack frame before making nested calls. It also preserves Callee-Saved registers ($s0, $s1) on the stack so the input argument n and intermediate results survive across nested invocations.

1. 피보나치 재귀 함수 어셈블리 코드1. Recursive Fibonacci Assembly Implementation

fibonacci_recursive.s
# int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); }
.text
.globl fib
fib:
    # 1. 스택 프레임 12바이트 확보
    addi $sp, $sp, -12
    sw   $ra, 8($sp)        # 복귀 주소 백업
    sw   $s0, 4($sp)        # 인자 n 백업용
    sw   $s1, 0($sp)        # fib(n-1) 결과 백업용

    move $s0, $a0           # $s0 = n

    # 2. 기저 조건 (n <= 1 이면 n 그대로 반환)
    li   $t0, 1
    ble  $s0, $t0, base_case

    # 3. 재귀 1: fib(n - 1)
    addi $a0, $s0, -1
    jal  fib
    move $s1, $v0           # $s1 = fib(n - 1)

    # 4. 재귀 2: fib(n - 2)
    addi $a0, $s0, -2
    jal  fib                # $v0 = fib(n - 2)

    # 5. 합산
    add  $v0, $s1, $v0      # $v0 = fib(n - 1) + fib(n - 2)
    j    fib_end

base_case:
    move $v0, $s0           # return n

fib_end:
    # 6. 스택 복원 및 복귀
    lw   $s1, 0($sp)
    lw   $s0, 4($sp)
    lw   $ra, 8($sp)
    addi $sp, $sp, 12
    jr   $ra
fibonacci_recursive.s
# int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); }
.text
.globl fib
fib:
    # 1. Allocate 12-byte stack frame
    addi $sp, $sp, -12
    sw   $ra, 8($sp)        # Save return address
    sw   $s0, 4($sp)        # Save callee-saved register for n
    sw   $s1, 0($sp)        # Save callee-saved register for fib(n-1)

    move $s0, $a0           # $s0 = n

    # 2. Base case (if n <= 1, return n directly)
    li   $t0, 1
    ble  $s0, $t0, base_case

    # 3. Recursive call 1: fib(n - 1)
    addi $a0, $s0, -1
    jal  fib
    move $s1, $v0           # $s1 = fib(n - 1)

    # 4. Recursive call 2: fib(n - 2)
    addi $a0, $s0, -2
    jal  fib                # $v0 = fib(n - 2)

    # 5. Sum results
    add  $v0, $s1, $v0      # $v0 = fib(n - 1) + fib(n - 2)
    j    fib_end

base_case:
    move $v0, $s0           # return n

fib_end:
    # 6. Restore stack frame and return
    lw   $s1, 0($sp)
    lw   $s0, 4($sp)
    lw   $ra, 8($sp)
    addi $sp, $sp, 12
    jr   $ra

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 임시 레지스터($t0~$t9) 사용 금지: jal fib를 호출하면 내부에서 $t 계열 레지스터와 $a0가 덮어써지므로, 호출 전후로 값이 유지되어야 하는 n과 fib(n-1) 결과는 반드시 Callee-Saved 레지스터($s0, $s1) 또는 스택 메모리에 보관해야 합니다.
  • 스택 포인터($sp) 대칭 복원: 함수 진입 시 addi $sp, $sp, -12로 내린 스택 포인터는 기저 조건(base_case)을 포함한 모든 반환 경로에서 반드시 addi $sp, $sp, 12로 복구한 뒤 jr $ra를 실행해야 합니다.
  • 지수적 호출 깊이와 스택 오버플로우: 순수 재귀 피보나치는 시간 복잡도가 $O(2^n)$이며 최대 호출 깊이가 $n$에 비례하므로, 큰 입력값에서는 스택 영역이 힙 영역을 침범할 수 있어 반복문이나 메모이제이션 적용을 권장합니다.
  • Do Not Store Live Values in Temporary Registers ($t0–$t9): Nested jal fib calls overwrite caller-saved $t registers and $a0, so values that must persist across a call (n and fib(n-1)) must reside in callee-saved registers ($s0, $s1) or stack slots.
  • Symmetric Stack Pointer ($sp) Restoration: Every exit path, including base_case, must branch to the epilogue (fib_end) to restore saved registers and increment $sp by 12 before executing jr $ra.
  • Exponential Call Depth and Stack Overflow: Naive recursive Fibonacci has $O(2^n)$ time complexity and $O(n)$ stack depth; for large inputs, prefer an iterative loop or memoization table to avoid exhausting stack memory.

MIPS 어셈블리에서 재귀 호출을 안정적으로 구현하려면 호출 규약에 따른 $ra 및 $s 레지스터의 스택 백업과 에필로그 단계의 정확한 복원 순서를 일관되게 유지해야 합니다.

Reliable recursion in MIPS assembly requires strict adherence to calling conventions—backing up $ra and $s registers in the prologue and restoring them symmetrically in the epilogue.

참고자료 & 관련 링크