RISC-V汇编实现矩阵阶乘

1) 源代码 

long long fact(long long n) {
	if (n < 1) return 1;
	else return (n*fact(n - 1));
}

2) 汇编代码 

fact:
    addi sp, sp, -16       // adjust stack for 2 items
    sd x1, 8(sp)           // save the return address
    sd x10, 0(sp)          // save the argument n
    addi x5, x10, -1       // x5 = n - 1
    bge x5, x0, L1         // if (n - 1) >= 0, go to L1
    addi x10, x0, 1        // return 1
    addi sp, sp, 16        // pop 2 items off stack
    jalr x0, 0(x1)         // return to caller

L1:
    addi x10, x10, -1      // n >= 1: argument gets (n - 1)
    jal x1, fact           // call fact with (n - 1)
    ld x6, 0(sp)           // restore argument n
    ld x1, 8(sp)           // restore the return address
    addi sp, sp, 16        // adjust stack pointer to pop 2 items
    mul x10, x10, x6       // return n * fact(n - 1)
    jalr x0, 0(x1)         // return to the caller

你可能感兴趣的:(risc-v,汇编)