//  *********************************************************************************************
//  Description      : Assembly instructions for fibonacci program
//  Project Version  : v1.0
//  Project          : [BCDC] Microtec Academy Course: Building a RISC-V CPU with SystemVerilog
//  -----
//  Copyright (c)    : 2025 Fraunhofer IIS, Department IDS
//  Created          : 15.Oct.2025  by Fuad Mammadzada
//  Last Modified    : 21.Oct.2025  by Fuad Mammadzada
//  -----
//  HISTORY          : Date         By         Comments
//                     -----------  ---------  -------------------------------------------------
//  *********************************************************************************************



#       Instruction                 # Hex code      # MemAddr(PC)   # Corresponding C code & explanation
_start:
        lui     sp, 2               # 0x00002137    # 0x00000000    # Initialize stack pointer value to size of memory (0x00002000)
        addi    sp, sp -4           # 0xFFC10113    # 0x00000004    # Subtract stack pointer value by 4 to point to the last memory address (0x00001FFC)
        jal     x0, main            # 0x0080006F    # 0x00000008    # Jump to main without saving the return address
halt:
        jal     x0, halt            # 0x0000006F    # 0x0000000C    # Halt the program (infinite loop)

main:                               # --------                      # fibonacci.c:17:   int main() {
        addi    sp, sp, -80         # 0xFB010113    # 0x00000010    # fibonacci.c:20:   int fib_number[20]; (allocate 20*4B from the stack)
        addi    a0, x0, 1           # 0x00100513    # 0x00000014    #                   a0 = 0 + 1 (this is later used in fibonacci.c:22)
        addi    a1, sp, 8           # 0x00810593    # 0x00000018    #                   calculate and save the address of fib_number[2]
        sw      x0, 0(sp)           # 0x00012023    # 0x0000001C    # fibonacci.c:21:   fib_number[0] = x0 = 0
        sw      a0, 4(sp)           # 0x00A12223    # 0x00000020    # fibonacci.c:22:   fib_number[1] = a0 = 1
        addi    a2, sp, 40          # 0x02810613    # 0x00000024    # fibonacci.c:24:   calculate the last array index for the loop condition (since n=10, n*4B)

.for_loop:
        lw      a3, -8(a1)          # 0xFF85A683    # 0x00000028    # fibonacci.c:25:   a3 = fib_number[i-2]
        add     a0, a3, a0          # 0x00A68533    # 0x0000002C    # fibonacci.c:25:   a0 = fib_number[i-1] + fib_number[i-2]
        sw      a0, 0(a1)           # 0x00A5A023    # 0x00000030    # fibonacci.c:25:   fib_number[i] = a0
        addi    a1, a1, 4           # 0x00458593    # 0x00000034    # fibonacci.c:24:   i++
        bne     a1, a2, .for_loop   # 0xFEC598E3    # 0x00000038    # fibonacci.c:24:   loop back if i != n
        jal     x0, halt            # 0xFD1FF06F    # 0x0000003C    # fibonacci.c:28:   asm("j halt");
