ARM中的递归Fibonacci

时间:2017-04-13 22:45:21

标签: recursion assembly arm fibonacci

我正在尝试将此递归Fibonacci代码转换为arm汇编语言。我是新手,并不确定如何做到这一点。我有一些我在下面玩过的代码片段。

  Fib (n) {
    if (n == 0 || n == 1) return 1;
    else return Fib(n-2) + Fib(n-1);
    }

到目前为止,这是我的尝试:

    RO = 1
    CMP RO #1
    BGT P2
    MOV R7 #1
    B END
P2:
    END LDR LR [SO,#0]
    ADD SP SP, #8
    MOV PC, LR

非常感谢帮助

1 个答案:

答案 0 :(得分:1)

为了避免吃勺,我写了一个LEGv8程序,使用递归找到Fibonacci序列。 LEGv8 略微与ARMv8不同,但算法仍然存在。

请查看代码,并将命令/寄存器更改为ARMv8中的相应值。

我假设n(Fibonacci序列的范围)存储在寄存器X19中。

我还假设我们应该将Fibonacci序列存储在一个数组中,该数组的基地址存储在X20中。

    MOV X17, XZR // keep (previous) 0 in X17 for further use
    ADDI X18, XZR, #1  // keep (Current) 1 in X18 for further use
    ADDI X9, XZR, #0  // Assuming i = 0 is in register X9
fibo: 
    SUBI SP, SP, #24 // Adjust stack pointer for 3 items
    STUR LR, [SP, #16] // save the return address
    STUR X17, [SP, #8] //save content of X17 on the stack
    STUR X18, [SP, #0] //save content of X18 on the stack
    SUBS   X10, X9, X19 // test for i==n
    CBNZ X10, L1 // If i not equal to n, go to L1
    MOV X6, XZR // keep 0 on X6    
    ADDI X5, XZR, #1 // keep 1 on X5 
    ADDI X2, X9, #1 //X9 increased by 1 for further use
    STUR X6, [X20,#0] //store 0 in the array
    STUR X5, [X20, #8] //store 1 in the array  
    ADDI SP, SP, #24 // pop 3 items from the stack
    BR LR // return to the caller 
L1: 
    ADD X16, X17, X18 // Next_Num = previous + Current
    MOV X17, X18 // Previous = Current
    MOV X18, X16 // Current= Next_Num
    ADDI X9, X9, #1 // i++
    BL fibo // call fibo
    LDUR X18, [SP, #0] // return from BL; restore previous
    LDUR X17, [SP, #8] // restore current
    LDUR LR, [SP, #16] // restore the return address
    ADDI SP, SP, #24 // adjust stack pointer to pop 3 items
    ADD X7, X18, X17 // keep (previous + current) value on register X7 
    LSL X2, X2, #3 // Multiplying by 8 for offset    
    ADD X12, X20, X2 // address of the array increase by 8
    STUR X7, [X12, #0] // store (previous + current) value on the array
    SUBI X2, X2, #1 // X9 decreased by 1 
    BR LR // return